# Question
Title: Commerce Feeds Node Parser Problem: product SKU "missing" from mappings causing empty product displays
I'm rebuilding a commerce site and I'm trying to use Commerce Feeds to bulk import my products. The issue that I'm having is that the node parser isn't mapping to the product SKU which is creating incomplete product displays. The title is imported, but most of the product display is empty until you manually set the SKU to the correct product. Doing this manually defeats the purpose of bulk importing them in the first place.

I even tried to import the working importer from my other site, but there the SKU mapping is labeled "Missing."

So, 1) what can I do that I don't have to manually set the SKU's for my products?

2) why is the product sku missing from the mapping options?

# Answer
> 0 votes
Found a similar problem in one of the issues, switched the dev version which solved my problem.

---
Tags: commerce, feeds
---


# Question
Title: How to measure time taken for a Feeds processing (benchmarking)?
Is there a way to measure time taken for a Feeds processing (benchmarking)? e.g. nodes / minute, time taken for last import. Similar to the statistics in Migrate UI?

# Answer
The Ultimate Cron module will tell you how long the import takes and keeps track of time for each feed import.

In your feed Basic Settings, for Periodic Import, make sure you set it to *As often as possible*.

In Ultimate cron, jobs tab, **Remember to run the scheduler cron job first,** then the Feeds cron jobs

Once you have a number, you can manually do the math on how many nodes per second.

**Note:** the cron run speed will vary based on your server machine. A more powerful machine will get the cron job done quicker.
> 1 votes

---
Tags: 7, feeds
---


# Question
Title: Private Message with node.js issues setting up
I have followed the suggested video tutorials https://www.youtube.com/watch?v=u1sxDaH3Z-U and https://www.youtube.com/watch?v=f8XAT1oB1eA

Im using the node.js watchdog submodule for debugging. That's what the tutorial video did. She didnt have any problems.

Any clues?

```
backendSettings = {
  "scheme":"http",
  "host":"localhost",
  "port":8989,
  "key":"/etc/nginx/ssl/SECURITY.key",
  "cert":"/etc/nginx/ssl/SECURITY.crt",
  "resource":"/socket.io",
  "publishUrl":"publish",
  "serviceKey":"",
  "backend":{
  "port":80,
  "host":"panduh420.com",
  "messagePath":"/nodejs/message"},
  "clientsCanWriteToChannels":true,
  "clientsCanWriteToClients":true,
  "extensions":"",
  "debug":false,
  "transports":["websocket",
  "polling"],
  "jsMinification":true,
  "jsEtag":true,
  "logLevel":1};

```

# Answer
> 1 votes
I had problems too. On line 3, for some reason using localhost never worked for me. Change line 3 to

```
"host":"panduh420.com",

```

Also, if your server has a firewall, make sure port 8989 is open.

Also, if you are not going to use https, then you don't need a key or cert.

here is mine

```
backendSettings = {
  "scheme":"http",
  "host":"mywebsite.com",
  "port":8080,
  "key":"/path/to/key/file",
  "cert":"/path/to/cert/file",
  "resource":"/socket.io",
  "publishUrl":"publish",
  "serviceKey":"",
  "backend":{
  "port":80,
  "host":"mywebsite.com",
  "messagePath":"/nodejs/message"},
  "clientsCanWriteToChannels":false,
  "clientsCanWriteToClients":false,
  "extensions":"",
  "debug":false,
  "transports":["websocket",
  "flashsocket",
  "htmlfile",
  "xhr-polling",
  "jsonp-polling"],
  "jsMinification":true,
  "jsEtag":true,
  "logLevel":1};

```

---
Tags: privatemsg, nodejs
---


title: Url params not working -> access denied

text:
# Question
Title: Url params not working -> access denied
I'm new to Drupal 8.

I tried to do some batch process (for example installing modules or importing language files).

I got access denied for example on this address : http://localhost/en/batch?id=17&op=start

I tried to investigate and debugging and find out in the file batch.inc

```
$request->get('id')

```

is Null

That means id=17 is not working.

What am i missing? Is it related to my Nginx server block config?

# Answer
> 0 votes
It was related to my nginx config and fast cgi params

using apache instead of nginx temporarily fixed he issue

---
Tags: uri, 8
---


# Question
Title: How do I modify a node's body (or any field) on display as `hook_node_view`?
So I am trying to upgrade my modules from Drupal 7 to 8 and some things have been pretty straightforward so far, but I'm stuck at a particular function that I just can't figure out how to implement on Drupal 8. Figuring out exactly how to make these changes on 7 was difficult enough, involving a lot of playing around with `print_r`. Maybe my approach last time was not the right way and therefore I'm already on the wrong track for Drupal 8. Anyway, I was trying to do a find and replace on node body text to change a pattern into a node URL. The code is below:

```
 function textreplace_node_view($node, $view_mode, $langcode){
   if($node->type == "article"){
     if(empty($node->content['body'])) return $node;
     $text = $node->content['body'][0]['#markup'];
     $offset = 0;
     $m = array();
     while ( preg_match('/\{\{nodeurl-([0-9]+)\}\}/', $text, $m, PREG_OFFSET_CAPTURE, $offset) ) {
       $offset = $m[0][1] + strlen($m[0][0]);
       $nod = (explode("-", str_replace("{{","",str_replace("}}","",$m[0][0]))));
       $nod = $nod[1];
       $thenode = node_load($nod);
       $text = str_replace($m[0][0], l($thenode->title, 'node/' . $nod), $text);
     }
     $node->content['body'][0]['#markup'] = $text;
     return $node;
   }
 }

```

I tried looking at how it was implemented in the Book module and the parameters started giving me errors when I changed them to what I saw in the Book module:

```
function book_node_view(array &$build, EntityInterface $node, EntityViewDisplayInterface $display, $view_mode) {

```

I was getting an error along the lines of `$node` must be of type EntityInterface...

Any help?

# Answer
> 2 votes
This should work, you are changing $build, which you don't need to return:

```
function textreplace_node_view(&$build, $node, $display, $view_mode) {
  // your code for $text
  $build['body'][0]['#text'] = $text;
}

```

---
Tags: hooks, 8
---


title: Mapping Drupal User to SalesForce User

text:
# Question
Title: Mapping Drupal User to SalesForce User
What is the best approach to map Drupal Users to the same user profile that is in SalesForce? Essentially I would want to add the User UID to their corresponding SalesForce User profile. But if there is a better way I would love to know. Thank you.

# Answer
You can use Salesforce module.

> This suite of modules supports integration with Salesforce by synchronizing Drupal entities with Salesforce objects

please refer to this link.
> 0 votes

---
Tags: 7, crm
---


# Question
Title: Print the location or filename of an uploaded file from a custom content type
I'm trying to figure out how to print out the file path and the name of the file uploaded from a custom content type. I have my template all setup and everything printing how I need to, the last thing is I just need to be able to print out the path or at least the name of the file from the upload attached to the content.

I tried using:

```
{{ node.field_name.value }}
{{ node.field_name.url }}
{{ node.field_name.content }}

```

# Answer
> 4 votes
The file field is an entity reference field, you can get the first file entity with `.entity`:

```
{{ node.field_downloads.entity.filename.value }}
{{ node.field_downloads.entity.uri.value }}

```

And access the fields of the file entity as usually.

If you have more than one file in the field:

```
second file:
{{ node.field_downloads.1.entity.filename.value }}
third file:
{{ node.field_downloads.2.entity.filename.value }}

```

---
Tags: 8, files
---


# Question
Title: Fatal error: Class 'SelectQuery' not found in /*/includes/database/database.inc on line 813
My site works fine in local system, Upload code and database in server show Error.

Fatal error: Class 'SelectQuery' not found in /\*/includes/database/database.inc on line 813

# Answer
> 0 votes
Check database setting in settings.php file. If database configuration is right then just clear the cache and rebuild registery.

---
Tags: 7, database
---


# Question
Title: How to remove rich text editor from user edit page?
I have noticed in user edit page that there is link called rich text editor in all user edit page, I want to remove it. Can anyone tell me how to remove that on user edit page?

# Answer
You can use Better formats module to show only formats role is authorized to use :
> 4 votes

---
Tags: users
---


# Question
Title: How to show logout link at the top right corner for non admin user
I want to show the logout link at top right of all pages, just like when we login as admin we could see logout link at the top right corner of the all pages, but problem is when I login as normal user \[non admin\] the logout link showing some where in the bottom, but I want to show it in the top right corner of all the pages please help me if anyone know!!

# Answer
> 0 votes
Yo have to create a block to list all page. Then use code.

```

if (!in_array("administrator", $roles)) {
use logout link here(user/logout)...........
}

```

First you have to check whether the user is anonymous.

---
Tags: users
---


# Question
Title: Getting 401 / 406 error from node creation with authentication
I am trying to create nodes with authentication with the services module enabled. So far I have done following things:

* Get services token from `http://localhost/drupal/services/session/token`.
* User authentication: I did trigger login web service and in return I got session name, id and complete user information. I called this web service by passing `X-CSRF-Token` which I got from previous web service. (http://localhost/drupal/myendpoint/user/login.json\`)
* Node creation: I want to create article content type node. I am passing fields values in JSON and CSRF token and session information as following. (`http://localhost/drupal/myrest/node.create`)

### Body (application/x-www-form-urlencoded)

```
{
   "title":"Created through service",
   "type":"article",
   "body": {
      "value": "<p>test</p>\n",
      "format": "filtered_html"
   }
}

```

### Headers

+ X-CSRF-Token: bla bla bla
    + \`SESSion name: bla bla bla

The response I received from node create web service is the following:

> Status Code: 406
> Date: Fri, 04 Dec 2015 23:43:31 GMT
> X-Content-Type-Options: nosniff
> Server: Apache/2.4.9 (Win32) OpenSSL/1.0.1g PHP/5.5.12
> X-Powered-By: PHP/5.5.12
> Content-Type: text/html
> Cache-Control: no-cache, must-revalidate, post-check=0, pre-check=0
> Connection: Keep-Alive
> Keep-Alive: timeout=5, max=100
> Content-Length: 0
> Expires: Sun, 19 Nov 1978 05:00:00 GMT

Could you please let me know what I am doing incorrect while triggering node create web service?

# Answer
> 0 votes
After digging much I found solution by my self:

I will post step by step process to create a node with authentication.

---

```
Step 1: Get initial token.

    URL: `http://localhost/drupal/services/session/token`

    Method: GET

```

---

```
Step 2: Login

    URL: `http://localhost/drupal/myrest/user/login.json`

    Method: POST

    Content-Type: application/json

    Request payload - request parameter:

    X-CSRF-Token: <Token received from first web service response>

```

---

```
Step 3: Create node.

    URL: `http://localhost/drupal/myrest/node`

    Method: POST

    Content-Type: application/json

    Raw body:

    `{
          "title": "Sample post",
          "type": "article"
     }`

     Custom headers - request parameters:

     <session_name_value_received_from_previous_service_response>: <session_id_value_received_from_previous_service_response>

     Example:

     SESS6a4470a2012aa23a7f83ea20ed1df766: KS43Muo_odeHA1KPI_kREWP6oK

     X-CSRF-Token: <token_value_received_from_previous_service_response>

     Example:

     X-CSRF-Token: JALApVoib7bGSFFh-59Saj9z5pT8q_5kP9BrHgGIO3E

```

---

And I am getting successful response:

`{"nid":"4","uri":"http://localhost/drupal/myrest/node/4"}`

Thanks all, please continue this thread if you face such issues. I will try to help.

# Answer
> 1 votes
Change the URL to `http://localhost/drupal/myrest/node`, the application type to application/json, and the request method to POST; then, it should work.

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


# Question
Title: How to translate a node without creating a new node?
I have translation enabled for the node type `page`, settings " Require language (Do not allow Language Neutral)." and " Normal - All enabled languages will be allowed".

However, when I'm creating and translating a node, it creates a new node instead of translating just the fields and storing the content in `$node->body["en_US"][0]`. How do I fix that?

# Answer
That is the way in which the Internationalization module works, when you go to translate a node the module create a copy in another language, if you want one node with the fields transalted you must look at the Entity Translation module.

You can read more in this in Node translation vs. Entity (field) translation
> 2 votes

---
Tags: i18n-l10n
---


# Question
Title: Updating a field programmatically, hook_node_update
Currently trying to update a field every time a node is created or updated. However the value is not being populated within the node, do I have access to the node object with this particular hook? What could I be missing?

```
  function vbtoken_node_update($node) {

      entity_get_controller('node')->resetCache(array($node->nid));

      $types = node_type_get_types(); //What are the current Node Content Types?
      $yes = ($types['volunteer_project']->type);

      if($node->type === $yes){

        $hash = md5($node->title . $node->nid . $node->nid);
        $hashed = substr($hash, 0, 6);
        $node = node_load($node->nid);
        $node->tcode[$node->language][0]['value'] = $hashed;
        node_save($node);

        watchdog('vbtoken', 'Added a new Token code to %nid', array('%nid' => $node->nid));

        }
        else
        {
          dpm('not working dude');
        }

    }

```

# Answer
> 16 votes
**Entity metadata wrappers**

The entity API provides some wrapper classes you may use to easily deal with entities and to leverage the entity property information modules provided. With the help of the wrappers you can access the property information, loop over known properties, or just get/set the described data values, etc.

These are some simple usage examples as found in the README:

For making use of this information (metadata) the module provides some wrapper classes which ease getting and setting values. The wrapper supports chained usage for retrieving wrappers of entity properties, e.g. to get a node author's mail address one could use:

```
$wrapper = entity_metadata_wrapper('node', $node);
$wrapper->author->mail->value();

```

To update the user's mail address one could use

```
$wrapper->author->mail->set('sepp@example.com');

```

or

```
$wrapper->author->mail = 'sepp@example.com';

```

The wrappers always return the data as described in the property information, which may be retrieved directly via entity\_get\_property\_info() or from the wrapper:

```
$mail_info = $wrapper->author->mail->info();

```

In order to force getting a textual value sanitized for output one can use, e.g.

```
$wrapper->title->value(array('sanitize' => TRUE));

```

to get the sanitized node title. When a property is already returned sanitized by default, like the node body, one possibly wants to get the not-sanitized data as it would appear in a browser for other use-cases. To do so one can enable the 'decode' option, which ensures for any sanitized data the tags are stripped and HTML entities are decoded before the property is returned:

```
$wrapper->body->value->value(array('decode' => TRUE));

```

That way one always gets the data as shown to the user. However if you really want to get the raw, unprocessed value, even for sanitized textual data, you can do so via:

```
$wrapper->body->value->raw();

```

More examples:

```
$wrapper->body->set(array('value' => "content"));
$wrapper->field_text[0] = 'the text';
$wrapper->field_text[0]->set(array('value' => "content"));
$wrapper->field_text2->summary = 'the summary';
$wrapper->field_text2->value = 'the text';

$wrapper->save();
$wrapper->delete();

```

**More docs**: http://drupal.org/node/1021556

# Answer
> 14 votes
Calling `field_attach_update('node', $node)` at the end of `hook_node_update` worked for me. I assume that `field_attach_insert('node', $node)` at the end of `hook_node_insert` would work, too. So, a sample function would look like this:

```
function mymodule_node_update($node) {
  $new_value = // ...do some stuff to compute a new value for the field.
  $node->field_my_field[LANGUAGE_NONE][0]['value'] = $new_value;
  field_attach_update('node', $node);
}

```

There's no need to call `node_load` `node_save` or to return anything.

I think the reason for this is that `node_save`, from which `hook_node_update` and `hook_node_insert` are called, wraps all database queries in a transaction. (Note the first line of `node_save`: `$transaction = db_transaction()`.) These queries aren't called until `node_save` finishes. The last query that `node_save` adds to the transaction is called from `field_attach_update`, which uses the $node object as it is *before* `hook_node_update` is called. So you need to queue up another query by calling `field_attach_update` again. At least, that's my understanding of what's going on.

If you're having trouble changing non-field attributes of the node (e.g., `$node->log`), try calling `_node_save_revision($node, $user->uid, 'vid');` too. This won't create a new revision.

# Answer
> 2 votes
This is how you change values on a node:

```
$node = node_load($nodeID);
$node->field_fieldname['und'][0]['value'] = $val;
node_save($node);

```

# Answer
> 2 votes
An improvement of Lance's solution above, avoiding the saving of a whole node when only a few field values are modified :

```
$node = node_load($nodeID);
// for each field whose value remains unchanged
unset($node->field_<field-name>);
// for each field whose value changes
$node->field_<field-name>[LANGUAGE_NONE][0]['value'] = <new-value>;
field_attach_update('node', $node);
entity_get_controller('node')->resetCache(array($node->nid));

```

This could also be useful to avoid side effects of `node_save()`.

Source : *Saving node's fields without saving the node itself*

https://www.urbaninsight.com/2011/10/24/saving-nodes-fields-without-saving-node-itself

---
Tags: 7, entities
---


# Question
Title: Does caching has to be manually disabled for ajaxified forms?
I switched on caching on my dev environment and it looks like ajaxified forms won't work\* unless I specifically set max-age to them to 0. Is this normal? Or is this the case only when a form is displayed via lazy builder?

\*they will work but submitting them will result in normal behavior where the form is submitted and the page is reloaded.

# Answer
> 0 votes
My issue was caused by the page\_cache module. It caches everything and I had wrong impression of how page\_cache and dynamic\_page\_cache are working. I have disabled the page\_cache module because I have some dynamic code that varies by the visitor so I cannot cache everything for anonymous users.

# Answer
> 1 votes
Not sure what you mean by "ajaxified". That sounds like a regular form is automatically "ajaxified".

Potentially this form is violating the principle that GET forms should not manipulate state. i.e. GET forms must be stateless. HTTP dictates this, but in Drupal 7 it was not respected. In Drupal 8 it is.

See https://www.drupal.org/node/2502785.

---
Tags: forms, ajax, 8
---


title: Display child items main navigation

text:
# Question
Title: Display child items main navigation
I created child elements for the main navigation. I went into the block configuration and adjusted it to show up to three levels of sub menu's.

For Drupal 7 I know that I used Nice Menu's to get the menu working with child links. But it's not usable yet with Drupal 8.

I was wondering if there was another module or how I could get my Child Links to show up.

# Answer
> 5 votes
You have to go to the menu configuration and manually check "expanded" for each item that has children. This is really annoying since there used to be a checkbox right on the list of links so you could do it on a single page at once. Not anymore.

---
Tags: 8, navigation
---


title: Redirect to another form on login

text:
# Question
Title: Redirect to another form on login
I have created a test site using drupal 7.

My requirement is to do an additional operation on user login. I need to redirect the users to another form when the user clicks on login button.

In this form there will be a question and 2 buttons 'update' and 'no'.

If the user chooses update a DB update will happen and also default login action.

But if the user chooses 'no' ,login should not happen.

I have already tried user\_login alter, multi-step forms and confirm\_form. But nothing seems to be working. Can anyone help.?

# Answer
> 1 votes
You can make your own login form (or alter default login form, i think) with two submit buttons calling different callback functions:

```
function xxx_login_form($form, &$state) {

  // .. usename and password fields here

  $form['submit_update'] = array(
    '#type' => 'submit',
    '#value' => t('Update'),
    '#submit' => array('xxx_login_submit_update'),
  );

  $form['submit_no'] = array(
    '#type' => 'submit',
    '#value' => t('No'),
    '#submit' => array('xxx_login_submit_no'),
  );

  return $form;

}

function xxx_login_submit_update($form, &$state) {

      if(user_authenticate($state['values']['username'], $state['values']['password'])) {
        // log in user
        $user_obj = user_load_by_name($username);
        $form_state = array();
        $form_state['uid'] = $user_obj->uid;
        user_login_submit(array(), $form_state);

        // .. do some updates

        return true;
      } else {
        return false;
      }

}

function xxx_login_submit_no($form, &$state) {

   // do what you need but do not log user in.

}

```

You can of course add custom validate functions, messages or what you need. If you want redirect to another page after button is pressed, you can use

```
'#action' => 'some/page/1'

```

for the buttons.

# Answer
> 0 votes
Login Toboggan provides that feature along with many other useful ones.

# Answer
> 0 votes
There are number of contributed module (like Login Toboggan) for such functionality but don't want to use contributed module. So you can do it with the help Rules and a custom module (to display confirmation form). You can also combine the rule in your custom module.

---
Tags: 7, redirection
---


# Question
Title: Conditional rewrite on views according to singular / plural
I am building a website using views and the answer module.

In my view, I add "Content: Answer Count" which is the number of answers.

I want to be able to rewrite the following output:
(1 Answer)
(2 Answers)
(3 Answers)
...

I know how to output "(no answers yet)" when the count=0.
But, how can I differentiate between singular and plural and output "Answer" or Answers" according to the count?

# Answer
> 1 votes
Drupal views provides a singular/plural option, if the field value is an integer type. In your case, if its not available in Field settings try using views\_php contrib module.

This module will allow you to add a field in views with php code that will executed on the fly. You can get existing values of row data inside php from `$data` variable. Now you can get your output based on the singular/plural in php.

But it is suggested to check the field settings properly if same option is available.

# Answer
> 0 votes
I am not sure you doing it in a custom manner, but there is `format_plural()` which is used for the same problem you have stated above. By default, almost every contributed and core module uses it, but in case if they are not, you will have to override them.

# Answer
> -1 votes
use a global field (math), which will give you the option of the plural formatter

---
Tags: views
---


# Question
Title: How to add a block to the main page region?
I want to add a simple blocks in the main page region. Instead of basic page or article I just want to add 4 blocks on that page. So, it looks like, Home page(Have blocks) \>\> sub-Home(have blocks) \>\> All Basic page(content). This looks simple but there is no way in the add block options where we can display as block and have a path.

# Answer
Go to YOUR\_SITE/admin/structure/block and find the ***Content*** region

then go to **Configure**

Then configure the **Visibility settings**, in this case this block only will be showed in the front page.
> 3 votes

---
Tags: 7, blocks
---


# Question
Title: Eliminate render-blocking JavaScript and CSS in above-the-fold content
I am building a Drupal 7 site. These are some of the modules I use: Adaptivetheme (theme), Views and Content Panes, Panels, Mini panels, Panels everywhere, Page manager, Superfish for menus, Addthis, Chosen (drop down).

For improving my site performance and the dealing with the CSS and JS files I am using the Advagg module.

When running the Pagespeed test of Google I am getting the following error as "Should Fix":

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

This is the info Google supplies:

Is there a way I can change the settings of the Advagg module or Drupal core, and solve this issue?

Is there another way to achieve this goal?

**Update** \- after implementing changes according to *mikeytown2* answer I got the following message on the Pagespeed test of Google:

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

# Answer
The README has a guide on how to do this using current 7.x-2.31+ version of AdvAgg. Also see this wiki page on the High performance group. Most sites can achieve a perfect 100/100 score on https://developers.google.com/speed/pagespeed/insights/. Directions on how to achieve it for a fresh of install of AdvAgg below.

Be sure to check the site after every section to make sure the change didn't mess up your site. The changes under AdvAgg Modifier are usually the most problematic but they offer the biggest improvements.

Advanced CSS/JS Aggregation

Go to `admin/config/development/performance/advagg`

* Select "Use recommended (optimized) settings"

AdvAgg Compress Javascript

Install AdvAgg Compress Javascript if not enabled and go to `admin/config/development/performance/advagg/js-compress`

* Select JSMin if available; otherwise select JSMin+
* Select Strip everything (smallest files)
* Click the batch compress link to process these files

AdvAgg Async Font Loader

Install AdvAgg Async Font Loader if not enabled and go to `admin/config/development/performance/advagg/font`

* Select Local file included in aggregate (version: X.X.X). If this option is not available follow the directions right below the options on how to install it.
* Check "Use localStorage so the flash of unstyled text (FOUT) only happens once."
* Check "Set a cookie so the flash of unstyled text (FOUT) only happens once."

AdvAgg Bundler

Install AdvAgg Bundler if not enabled and go to `admin/config/development/performance/advagg/bundler`

*HTTP/2.0 Settings*

* Under "Target Number Of CSS Bundles Per Page" select 25
* Under "Target Number Of JS Bundles Per Page" select 25
* Under "Grouping logic" select "File size"

*HTTP/1.1 Settings (default)*

* Under "Target Number Of CSS Bundles Per Page" select 2
* Under "Target Number Of JS Bundles Per Page" select 5
* Under "Grouping logic" select "File size"

25 bundles vs 2 and 5 has to do with browser caching. More files equals a better chance of the browser having that combo in its cache, but more files means more connections being established and opened in HTTP 1.1. Use 2 for CSS as this number doesn't wait for any new connections; JS is 5 as most browsers have a concurrent connections limit of 6. This number for bundles was picked after many tests. In HTTP 2.0 there is one streaming connection and the penalty for multiple CSS and JS files is almost non existent; thus optimizing for the browser cache is the best choice; thus 25 should be used for CSS and JS when serving HTTP/2.0.

AdvAgg Relocate

Install AdvAgg Relocate if not enabled and go to `admin/config/development/performance/advagg/relocate`

* Select "Use recommended (optimized) settings"

AdvAgg Modifier

Install AdvAgg Modifier if not enabled and go to `admin/config/development/performance/advagg/mod`

* Select "Use recommended (optimized) settings"

Generating Critical CSS Files

Go to https://www.sitelocity.com/critical-path-css-generator and input as many landing pages as needed for critical css; the top 10 is usually a good start. If you have Google Analytics this will show you how to find your top landing pages https://developers.google.com/analytics/devguides/reporting/core/v3/common-queries#top-landing-pages or for Piwik https://piwik.org/faq/how-to/faq\_160/. If you don't know what page to start with do your site's homepage. You can also us this to generate css https://chrome.google.com/webstore/detail/critical-style-snapshot/gkoeffcejdhhojognlonafnijfkcepob?hl=en

Example filenames and paths below are for the "bootstrap" theme; they all start with `sites/all/themes/bootstrap/critical-css/`; in your theme create the `critical-css/` directory. The next directory is based on the user; `anonymous/`, `all/`, or `authenticated/` can be used.

The next directory can be `urls/` or `type/`. Looking at `urls/`; front is a special case for the front page, all other paths use current\_path() as the directory and filename with `.css` added to the end; See https://api.drupal.org/api/drupal/includes%21path.inc/function/current\_path/7.x

Looking at `type/` this is a special case for node types. Use the machine name and add `.css` to the end. Any node of this type will then have this critical css file applied and inlined. Below are some examples showing how this works.

valid example file locations for the "front" page: `sites/all/themes/bootstrap/critical-css/anonymous/urls/front.css`

valid example file locations for "node/1" current\_path() page: `sites/all/themes/bootstrap/critical-css/anonymous/urls/node/1.css`

valid example file locations for the node type of "page": `sites/all/themes/bootstrap/critical-css/anonymous/type/page.css`

If you want some sort of automated way to generate these css files fourkitchens has an excellent article on how to set that up: https://fourword.fourkitchens.com/article/use-grunt-and-advagg-inline-critical-css-drupal-7-theme
> 44 votes

# Answer
You will never get truly high scores with prebuilt drupal modules, the only way to achieve this is by attending and carefully analyzing each the the suggestions made by the google speed tool, addressing each of those independently.

Some things I did to achieve 95 in a very active news site, that by the time I wrote this, scored better than nytimes (Now it doesn't):

* \[blocking scripts\] Delay execution of third party scripts like sharethis, facebook widgets, google plus, etc, to run only after the page has been fully rendered. This required some simple string replacements to on the output of html.tpl.php to catch those scripts and queue them for later execution.
* \[blocking scripts\] Store the $scripts variable of html.tpl.php (with json\_encode) in a javascript variable to queue them for running after the first page load. This is unnatural, but necessary. Some browser specific issues had to be sorted out.
* \[blocking css\] Implemented something similar to the Keith Clark's technique, but with rel="prefetch". This introduces the need to solve the FOUC.
* \[Minification and compression\] Externalize compression and minification to a distribution server where I can use imagemagic, yui-compressor, pngoptim and more stuff to overcome those rules, without turning the drupal install into an unmanageable mess.
> 2 votes

---
Tags: 7, theming, javascript, performance
---


# Question
Title: Migrating orders doesn't migrate total values
Has anyone tried migrating commerce orders? I had problems tracing the tables that was used by commerce order.

Initially, I've already mapped commerce\_order\_total and commerce\_order\_total:currency\_code (in the ui: http://prntscr.com/9a6bid). My query from the source database also outputs correctly. My problem is after migrating, commerce total values were not migrated (http://prntscr.com/9a6cko).

Am I in the right track? Please help.

I'm also confused why commerce\_line\_item is needed in commerce order and order\_id is needed in commerce line item. I'm really confused.

Are there any existing useful links regarding this?

Thanks for any help!

# Answer
The bi-directional link is a relic of the Drupal 7 entity API at the time we wrote Drupal Commerce 1.x. It was basically a DX concession of dubious benefit, but we'll be fixing that in 2.x. ; )

As for how order totals are calculated, order save automatically calculates the total by summing up all of the price components in the "total" price fields on line items. If you haven't properly set the associations in your line items or if you haven't set the price component arrays for the line items you've created, your order total will not calculate properly.
> 1 votes

---
Tags: 7, commerce, migrations
---


title: How to create 'Partial' Search?

text:
# Question
Title: How to create 'Partial' Search?
I'm using Drupal commerce and I was wondering if there is a way to do partial search? Current the search engine is only searching the exact word. E.g. Candy or Battery I'm looking to search with only term 'Can' or 'Bat'. Please advise. Thank you

# Answer
You'll want to employ some sort of stemming algorithm for that.

The Porter-Stemmer module is a possible choice:

> This module implements the Porter stemming algorithm to improve English-language searching with the Drupal built-in Search module.
> 0 votes

# Answer
1.On yoursite/admin/config/search/search\_api/ choose "*edit*" your server type (not index type)configuration.

2.At the bottom of the page set the "*Search on parts of the word*"checkbox checked.
> 0 votes

---
Tags: commerce, search
---


# Question
Title: Filter a view by a field on a referenced entity
Sorry to be yet another question about entry reference relationships in views, but I can't find the answer in pre-existing questions.

Given:

* the content type "page" has an entity reference field "artref" that references multiple nodes of the content type "article"
* the content type "article" has a boolean field "fishy"

How do I create a view that shows all pages which reference at least one article where fishy is checked.

I understand that here are 4 relevant settings:

* the basic entity bundle (pages or articles) selected for the view
* the relationship type ("content referenced from" or "content using")
* "require this relationship" setting
* Aggregation, especially if "distinct" is a possibility

All advice much appreciated

# Answer
> 1 votes
I figured it out. Configure in this sequence:

* Show: "content" of type "page"
* Relationships: "Content referenced from art\_ref"
* Use Aggregation: Yes
* Add filter criteria: fishy, Aggregation: "group results together", relationship: "art\_ref:content", operator: "is equal to" "1"

# Answer
> 0 votes
1. Create new content type,for example, "Article\_1",having "fishy" field of boolean type.
2. Create new content type "Page\_1",having entity reference field "artref" to "Article\_1" content type. Values - unlimited.
3. Create new View with filter criteria Content:Type="Page\_1".
4. In view "advanced" section add Relationship:"Content entity referenc**ed**(not referenc**ing**) from field\_artref". "Require this relationship" you may live unchecked.
5. Add new filter criteria is based on "fishy" field = "Yes", for example.("Yes" is "On value" and "No" is a "Off value" for boolean "fishy" field).
6. Set relationship for this filter criteria to "Content entity referenced from field\_artref".
7. **In "advanced" section open "Query settings:settings" and set to checked "Distinct" checkbox.**

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


# Question
Title: How to allow users to post content and easily overrule its default access settings?
On our website, we have a content type ("*news*"), which includes both public and private items. Normally, posts will be viewable by authenticated users only. However, I want to allow people to post content that is viewed publicly. The way I would prefer to do this is with a simple checkbox during node creation, which allows the node to be public, and viewable for anonymous users.

So far, I've tried the Content Access module, but the interface it provides is too complicated; I only need a checkmark for "*allow anonymous to view*".

# Answer
> 2 votes
You can get this to work using a combination of the Rules module and the Content Access module, whereas the Rules module will automatically (behind the scenes) trigger the logic that's needed. The logic itself is entirely hidden for the user (author) and is equivalent to using the interface that you consider too complicated.

Here are some more details to get it to work:

1. Start from a rule that is similar to the example I included in my answer to "How to specify a Rules condition related to select list values?".
2. This sample rule uses a field named `field_optionlist`, with 3 possible values A,B,C. In your case you could use any other fieldname (to fit your naming conventions). And your field only needs 2 values, say `Y` (= yes, instead of `A`) and `N` (= no, instead of `B`). Some more tips to get you going:

* Make sure to define this field (for your content type `news`) BEFORE importing the rule sample in item '1.' above (if not the import of the rule will fail).
    * If you use another machine name for that field, also edit the field name in the sample rule before importing it.
    * Adapt the Rules condition related to "value = `C`" to "value = `Y`" (to fit your case), and the message included in the Rules Action.
3. QA-test the intermediate result after completing step '2.': you should have a Drupal message show up when a `news` node is created with field value = `Y` (and not when it is not `Y`).
4. Use the integration of the Content Access module with the Rules module to create a Rules Action that updates the access of the node, similar to the Rules Action I included in my sample rule included in my answer to the question "How to revoke edit access to the node's author after publishing a node?". The actual settings to use for the content access module should match with the settings you seemed to already have tried (but which you consider as too complicated to have the node editor set them).

**Refinement**: if you really want a "checkmark" (instead of such yes/no selection field explained above), create a boolean field and rework the rule detailed above to use that field instead.

**Bonus**: if you ever need similar logic for another content type, just define the SAME field (with same machine name). After doing so, you should not have to change anything to the Rule as defined above. That's because of the "entity has field" condition ...

---
Tags: users
---


# Question
Title: How do I send a drupal_http_request() with GET method?
Following examples found here and in API, I tried 2 methods, both return a **bad request** status message.

## First method

```
$data = 'name=value&name1=value1';

$options = array(
  'method' => 'GET',
  'data' => $data,
  'timeout' => 15,
  'headers' => array('Content-Type' => 'application/x-www-form-urlencoded'),
);

$result = drupal_http_request('http://example.com/foo', $options);

dpm($result);

```

## Second method

```
$data = array(
  'key1' => $value1,
  'key2' => $value2,
);

$full_url = url('http://example.com/foo', array('query' => $data));

$options = array(
  'method' => 'GET',
  'timeout' => 15,
  'headers' => array('Content-Type' => 'application/x-www-form-urlencoded'),
);
$result = drupal_http_request($full_url, $options);

dpm($result);

```

Which one is the good one and what's wrong ? Thank you

## Edit

This is `dpm($result)`

# Answer
The first method is correct; you should not use `url()` for an external URL that is passed to `drupal_http_request()`, except (for example) when you want other modules to alter the hook via their `hook_url_outbound_alter()` implementations, or you want to let `url()` split off the fragment (or the query) from the URL. (The fragment is used to set `$options['fragment'], when it's not already set; the query is added to` $options\['query'\].

The code run by `url()` for an external URL is the following one. (I showed only the relevant code; where I omitted code, I used an `// Omissis` comment. I also removed the original comments from the code and added mine to evidence some code parts.)

```
if (!isset($options['external'])) {
  $options['external'] = $path === $_GET['q'] ? FALSE : url_is_external($path);
}

// Omissis

if ($options['external']) {
  if (strpos($path, '#') !== FALSE) {
    list($path, $old_fragment) = explode('#', $path, 2);
    if (isset($old_fragment) && !$options['fragment']) {
      $options['fragment'] = '#' . $old_fragment;
    }
  }

  if ($options['query']) {
    $path .= (strpos($path, '?') !== FALSE ? '&' : '?') . drupal_http_build_query($options['query']);
  }

  // Change the URL protocol basing on a Drupal local setting.
  if (isset($options['https']) && variable_get('https', FALSE)) {
    if ($options['https'] === TRUE) {
      $path = str_replace('http://', 'https://', $path);
    }
    elseif ($options['https'] === FALSE) {
      $path = str_replace('https://', 'http://', $path);
    }
  }

  return $path . $options['fragment'];
}

```

Apart from what I reported before, there isn't much any pro in using `url()` when used for a string you already know it contains an external URL. The part commented with `Change the URL protocol basing on a Drupal local setting.` only changes the used protocol basing on the value of `$options['https']`, when a local Drupal settings has been set to `TRUE`. For a string that contains already an external URL, which is then passed to `drupal_http_request()`, that code isn't much helpful; you would know already if the external URL needs to be accessed via https:// or http://, and you would not want to change the used protocol basing on a local setting.

*application/x-www-form-urlencoded* is the content type used when POSTing data, while you are GETting data.

To build the query data, you could also use `drupal_http_build_query()`, which the same function used from `url()` for the same purpose.

```
$data = array('name' => 'value', 'name1' => 'value1');

$options = array(
  'method' => 'GET',
  'data' => drupal_http_build_query($data),
  'timeout' => 15,
);

$result = drupal_http_request('http://example.com/foo', $options);

```
> 3 votes

---
Tags: http-request
---


# Question
Title: Is there any way to add comments to pages which are NOT nodes
Im building a module and need to put a comments form on a page which is **NOT a node**. Is there a way of doing this?

I guess I will need to use:

> drupal\_get\_form('comment\_form', array('nid' =\> $node-\>nid));

However this seems to have a certain dependency on the nid as it always seems to be attached to a node.

# Answer
API the module that handle the pages you see at api.drupal.org, has the same problem; the documentation pages you see are not nodes, but the module allows to add comments to them.

The page callback invoked for the documentation pages is api\_page\_function(), which is associated to the path `api/%/%/function/%api_item` in its implementation of `hook_menu()` (see api\_menu(), starting at line 125 of the linked file). The page callback uses \_api\_add\_comments(), which contains the following code:

```
if (module_exists('comment') && user_access('access comments') && variable_get('comment_api', COMMENT_NODE_READ_WRITE) != COMMENT_NODE_DISABLED) {
  $output .= comment_render(node_load($documentation_object->did));
  if (user_access('post comments')) {
    $output .= comment_form_box(array('nid' => $documentation_object->did), t('Post new comment'));
  }
  // ...
}

```

API creates empty nodes that associate to the documentation pages; the reason of this is that the Comment module still need a node object to return any comment that is associated with that node.
> 3 votes

# Answer
No. A comment has a required foreign field in the database: "comments.nid". Comments will not do for anything that is not a node.

Even if you somehow manage to store comments without a node Id, things will break hooribly.
> 1 votes

# Answer
I suggest trying the Reply module.
> 1 votes

# Answer
This works for me:

```
if (module_exists('comment') && user_access('access comments') && variable_get('comment_api', COMMENT_NODE_READ_WRITE) != COMMENT_NODE_DISABLED) {
  $output .= comment_render(node_load($documentation_object->did));
  if (user_access('post comments')) {
    $output .= comment_form_box(array('nid' => $documentation_object->did), t('Post new comment'));
  }
  // ...
}

```

But I work with the ajax\_comments module when trying to save a comment it's got to replay pages.

But all the tags and ajax\_comment.js and .css is loaded and the structure for the form is with the node page (any solution for this).
> 1 votes

# Answer
It is definitely possible to add comments to none-node pages. I follow ideas in other answers to attach an empty node to my none-node page. All the technical details are here.

**Use case:**

I migrate an old website to Drupal 7. I have old URLs showing the content of a database table like http://www.example.com/oldpage.php?gid=xxxxx where xxxxx is an interger ID. These IDs are important to me as there are thousands of links from external sites to them. My new Drupal URLs look like http://www.example.com/newpage/xxxxx I can always let the web server rewrite old URLs to the new URLs. If I use node, I no longer have control over the IDs.

**Map old ID to new node ID:**

I create a new node type called '*empty node*'. This can be done using the admin user interface or by Drupal API. Next create a database table called *association\_table* like this:

```
+------------+-------------+------+-----+---------+-------+
| Field      | Type        | Null | Key | Default | Extra |
+------------+-------------+------+-----+---------+-------+
| drupal_nid | int(11)     | NO   | PRI | NULL    |       |
| gid        | int(8)      | YES  |     | NULL    |       |
+------------+-------------+------+-----+---------+-------+

```

This maps my old 'gid' to the associated node ID of 'empty node'. An empty node will be created as needed when user visit my newpage URL. At the end of that page I have something like:

```
$sql = "SELECT drupal_nid from {association_table} WHERE gid=". $gid; // $gid: my old ID
$results = db_query($sql);
if ($results->rowCount()==1) {
  // already associated with an empty node
  $nid = $results->fetchField(0);
}
else {
  // call helper function to create a new empty node and return its node id
  $nid = mymodule_new_node($title);
  // create new entry in association_table
  $sql = "INSERT INTO {association_table} VALUES(". $nid. ", ". $gid. ")";
  db_query($query); // I keep things simple here, of course use Drupal way to insert.
}

```

Now the helper function:

```
function mymodule_new_node($title) {
  $node = new stdClass();
  $node->type = 'empty_node';
  $node->title = $title;
  $node->uid = 1;  // created by admin user
  if (module_exists('comment')) {
    $node->comment = variable_get('comment_api', COMMENT_NODE_OPEN);
  }
  node_save($node);
  return $node->nid;
}

```

The helper function creates an empty node, set its title to something appropriate, set its owner to admin user, and return its node id. The *$title* bit is absolutely necessary. The title will appear in many places in Drupal, such as 'admin/content', 'admin/content/comment', and the clickable links in search result.

**Append comment form to none-node page:**

This is fairly easy to do. At the end of my 'newpage', do

```
if (module_exists('comment') && user_access('access comments') && variable_get
('comment_api', COMMENT_NODE_OPEN) != COMMENT_NODE_HIDDEN) {
  $comment_form = comment_node_page_additions(node_load($nid));
  $output .= drupal_render($comment_form);
}

```

With this form, user can add comment to the main comment table.

**Handle redirection:**

Drupal will refer to these empty nodes using URL /node/????? (e.g. links in 'admin/content'). When users submit the comment form they will too be redirected to /node/?????. I need to redirect /node/????? to /newpage/xxxxx using the mapping in the association\_table. This is done by implementing *hook\_node\_view*:

```
function mymodule_node_view($node, $view_mode, $langcode) {
  if ($node->type == 'empty_node' && $view_mode == 'full' && arg(0) == 'node') {
    $sql = "SELECT gid FROM {association_table} WHERE nid=". $node->nid;
    $gid = db_query($sql)->fetchField(0);
    drupal_goto('newpage/' . $gid);
  }
}

```

**Summary:**

This procedure works flawlessly for me on my Drupal 7 production site.

There are some additional tweaks that are required. For example, depending on how the titles of the empty nodes are set, they might appear in search result. This might not be desirable. In my case, I use *hook\_query\_alter* to change how search is done on these empty nodes.
> 0 votes

---
Tags: 7, comments
---


title: Back to views search result

text:
# Question
Title: Back to views search result
View search results gives node list based on exposed filters applied when making the search.

After user picks a result (node) and reads it there is no easy way to get him back to search results.

Exposed filters are "remembered", but the option to click back in browser does not seem user friendly, so i am looking for a module to do this. Is there any ?

# Answer
Maybe you could check the selected answer here How to provide back link to page? just to confirm if you really want this kind of functionality and it also suggests some options that you can do and it's "non-recommended" level.

Hope that helps.
> 0 votes

---
Tags: 7, views
---


# Question
Title: Commerce Rule For Sales Tax On Shipping To One State
We want to only apply sales tax on orders shipped to a particular State. I tried to cobble together the following rule from the included 'Price Component' and it seems to apply tax on shipping for -all- orders, regardless of the address component.

Can someone look at this and tell me what I'm doing wrong?

```
{ "rules_apply_taxes_to_shipping" : {
    "LABEL" : "Apply Taxes to Shipping",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "commerce_order", "commerce_tax", "commerce_shipping" ],
    "ON" : { "commerce_shipping_calculate_rate" : [] },
    "IF" : [
      { "commerce_order_compare_address" : {
          "commerce_order" : [ "commerce-line-item:order" ],
          "address_field" : "commerce_customer_shipping|commerce_customer_address",
          "address_component" : "administrative_area",
          "value" : "WA"
        }
      }
    ],
    "DO" : [
      { "commerce_tax_calculate_by_type" : {
          "commerce_line_item" : [ "commerce_line_item" ],
          "tax_type_name" : "sales_tax"
        }
      }
    ]
  }
}

```

Here is the Rules Evaluation Log. Apparently the rule isn't even firing. How do I figure -that- out?

```
    0 ms Reacting on event Calculating the sell price of a product.
    3.479 ms Evaluating conditions of rule Calculate taxes: VAT. [edit]
    3.489 ms AND evaluated to TRUE.
        0 ms Rule Calculate taxes: VAT fires.
        0.138 ms Evaluating the action commerce_tax_calculate_by_type. [edit]
        4.267 ms Rule Calculate taxes: VAT has fired.
    7.837 ms Evaluating conditions of rule Calculate Bundle Product Price. [edit]
    7.845 ms AND evaluated to TRUE.
        0 ms Rule Calculate Bundle Product Price fires.
        0.093 ms Evaluating the action commerce_product_bundle_calculate_price. [edit]
        4.688 ms Rule Calculate Bundle Product Price has fired.
    12.594 ms Evaluating conditions of rule Quote Required. [edit]
    12.609 ms AND evaluated to TRUE.
        0 ms Rule Quote Required fires.
        0.012 ms Rule Quote Required has fired.
    12.692 ms Evaluating conditions of rule Calculate taxes: Sales tax. [edit]
    12.699 ms AND evaluated to TRUE.
        0 ms Rule Calculate taxes: Sales tax fires.
        0.111 ms Evaluating the action commerce_tax_calculate_by_type. [edit]
            0 ms Executing rule Calculate Sample Michigan Sales Tax 6%.
            0.169 ms Evaluating conditions of rule Calculate Sample Michigan Sales Tax 6%. [edit]
            2.254 ms The condition commerce_order_compare_address evaluated to TRUE [edit]
            2.263 ms AND evaluated to TRUE.
                0 ms Rule Calculate Sample Michigan Sales Tax 6% fires.
                0.089 ms Evaluating the action commerce_tax_rate_apply. [edit]
                0.571 ms Added the provided variable applied_tax of type commerce_price [edit]
                0.6 ms Rule Calculate Sample Michigan Sales Tax 6% has fired.
            2.905 ms Finished executing of rule Calculate Sample Michigan Sales Tax 6%.
        5.114 ms Rule Calculate taxes: Sales tax has fired.
    17.894 ms Evaluating conditions of rule Unset the price of disabled products in the cart. [edit]
    18.145 ms The condition data_is_empty evaluated to FALSE [edit]
    18.334 ms The condition entity_has_field evaluated to TRUE [edit]
    19.067 ms The condition data_is evaluated to FALSE [edit]
    19.076 ms AND evaluated to FALSE.
    19.102 ms Evaluating conditions of rule Quote Required. [edit]
    19.195 ms The condition data_is_empty evaluated to FALSE [edit]
    19.296 ms The condition entity_has_field evaluated to TRUE [edit]
    19.708 ms The condition data_is evaluated to FALSE [edit]
    19.716 ms AND evaluated to FALSE.
    19.737 ms Finished reacting on event Calculating the sell price of a product.

```

# Answer
> 0 votes
No idea why your rule isn't triggering based on the state. From the label, it looks like you're trying to apply taxes to the order total including shipping. So you need two things here you need to configure a state specific tax rule and then you need a shipping rule, and a second shipping rate calculation which applies your tax to your shipping rate. Hope that helps.

---
Tags: rules, commerce
---


# Question
Title: Commerce Kickstart 2 Need Rule To Apply Sales Tax To Shipping
I need a Rule to apply sales tax to shipping on a sales order.

I tried the following code (borrowed from here: https://www.drupal.org/node/2307695) and it doesn't work for me:

```
{ "rules_apply_sales_tax_to_shipping" : {
"LABEL" : "Apply sales tax to shipping",
"PLUGIN" : "reaction rule",
"WEIGHT" : "5",
"OWNER" : "rules",
"REQUIRES" : [ "commerce_tax", "commerce_shipping" ],
"ON" : { "commerce_shipping_calculate_rate" : [] },
"DO" : [
{ "commerce_tax_calculate_by_type" : {
"commerce_line_item" : [ "commerce_line_item" ],
"tax_type_name" : "sales_tax"
}
}
]
}
}

```

Maybe there is a typo? There are only two tax\_types on our site, sales\_tax and VAT so I don't think so.

Do I need to add this as an Action onto our Sales Tax? I don't see how to do this... this does not appear in the drop down list of available Actions.

# Answer
don't know if you solved this yet (hope so). The trick is to set your tax rate and THEN apply is a calculation rule to shipping. Not the most intuitive way to do it, but it works.
> 0 votes

---
Tags: commerce
---


# Question
Title: Blocks created using multiblock module are not working
1. Installed multiblock module.
2. Create duplicated blocks (structure \> block \> instance \> create .. ) and placed them in footer1 region.
3. Original blocks are in very-top1 region.

Duplicated blocks are menu links. When I click those links, nothing happens. They definitely worked before. I am not sure why they dont work now. I must done something wrong.

My site address: http://godrupal.info/. If you scroll to the bottom you will see the all the links. Do you know why those duplicated links are not working?

# Answer
> 1 votes
I checked your site out specifically the footer area as you've instructed. This is not the module's issue but a Bootstrap/theming issue. Notice in the screenshot:

The block-9 block is using the col-md-12 which spans the whole content area and covering everything under it that's why the links aren't clickable.

I tested and just changed col-md-12 into col-md-2 and now the links are clickable.

Please check your markup and CSS to confirm.

---
Tags: blocks
---


# Question
Title: Duplicate field values in views for a custom entity
I have a custom entity. I'm using hook\_entity\_property\_info() to tell views what fields are in my custom entity.

However for some reason I am getting duplicate fields when it comes to views. As in, I go to add a field in a view, and it is listed twice. It's not a problem, but cosmetically it is ugly.

Why would this be?

I am using this as my views controller class:

```
'views controller class' => 'EntityDefaultViewsController',

```

Could that be the problem?

This is the link that is most relevant to what I am doing:

https://www.drupal.org/node/1208874

My hook\_entity\_property\_info():

```
/**
 * Implements hook_entity_property_info().
 */
function stockinfo_historical_entity_property_info() {
  $info = array();

  $info['stockinfo_historical']['properties']['sid'] = array(
    'label' => t('SID'),
    'description' => t('The ID of the stockinfo historical row.'),
    'type' => 'stockinfo_historical',
    'schema field' => 'sid',
    'entity views field' => TRUE,
  );
  $info['stockinfo_historical']['properties']['symbol'] = array(
    'label' => t('Symbol'),
    'description' => t('Symbol of the stock.'),
    'type' => 'text',
    'schema field' => 'symbol',
    'entity views field' => TRUE,
  );
  $info['stockinfo_historical']['properties']['name'] = array(
    'label' => t('Company Name'),
    'description' => t('Name of the company.'),
    'type' => 'text',
    'schema field' => 'name',
    'entity views field' => TRUE,
  );
  $info['stockinfo_historical']['properties']['date'] = array(
    'label' => t('Date'),
    'description' => t('The day this happened on.'),
    'type' => 'date',
    'schema field' => 'date',
    'entity views field' => TRUE,
  );
  $info['stockinfo_historical']['properties']['stockinfo_historical_high'] = array(
    'label' => t('High'),
    'description' => t('The high on this day.'),
    'type' => 'decimal',
    'schema field' => 'stockinfo_historical_high',
    'entity views field' => TRUE,
  );
  $info['stockinfo_historical']['properties']['stockinfo_historical_low'] = array(
    'label' => t('Low'),
    'description' => t('The low on this day.'),
    'type' => 'decimal',
    'schema field' => 'stockinfo_historical_low',
    'entity views field' => TRUE,
  );
  $info['stockinfo_historical']['properties']['stockinfo_historical_close'] = array(
    'label' => t('Close'),
    'description' => t('The close on this day.'),
    'type' => 'decimal',
    'schema field' => 'stockinfo_historical_close',
    'entity views field' => TRUE,
  );
  $info['stockinfo_historical']['properties']['stockinfo_historical_volume'] = array(
    'label' => t('Volume'),
    'description' => t('The volume on this day.'),
    'type' => 'decimal',
    'schema field' => 'stockinfo_historical_volume',
    'entity views field' => TRUE,
  );
  $info['stockinfo_historical']['properties']['stockinfo_historical_adj_close'] = array(
    'label' => t('Adjusted Close'),
    'description' => t('The adjusted close on this day.'),
    'type' => 'decimal',
    'schema field' => 'stockinfo_historical_adj_close',
    'entity views field' => TRUE,
  );
  return $info;
}

```

# Answer
Setting EntityDefaultViewsController is not really required as entity API sets this by default and yes it does conflict with `hook_entity_property_info()`.

The solution can be found here: https://www.drupal.org/node/1208874 and it is as simple as defining the 'module' property in `hook_entity_info().`

```
<?php
/**
 * Implements hook_entity_info().
 */
function entity_test_entity_info() {
  return array(
    'entity_test' => array(
      'label' => t('Test Entity'),
      // Entity API needs to know about your module for the views integration to work
      'module' => 'entity_test',
     ..
?>

```

Once the 'module' property is defined the entity API will no longer try to guess the property types and follow `hook_entity_property_info()` implementation.

This same trick also solved errors related to string and array conversions I was having such as:

> strpos() expects parameter 1 to be string, array given in entity.property.inc:363
> 0 votes

---
Tags: views
---


# Question
Title: How do I have menu linked content not on main page?
My web site is the first drupal site I have made. And after I made it, I left it to do other work -- like write the blogs for the site. I cannot remember how I set up the content pages that link to menu selection that do not appear as content on the main page.

The best way to explain what I am talking about is with a screen capture. I have added menu items to my main menu. I do not remember how I did it in the past. I want to add content and have it linked to the main menu (this option is available to me when I create the content) but I do not want them to appear as stories on the main page.

The circled areas in this screen shot shows the menu item I just added and the corresponding item on the main page that I do not want to be there. How do I remove it from the main page?

I am thinking that perhaps I should not have added it as a "content" but something else? If so, what and how?

http://www.arguemax.com/images/problems/12-6-2015/Capture\_001.PNG

# Answer
When you create the Content, be sure to uncheck "Promoted to front page" in the option menu shown at the bottom, under **Published options**. See image.

If you want this option by default for a specific content type (for example, for **Articles**) you will need to go to **Structure \> Content types** and edit that content type's **Publishing options** to uncheck **Promoted to front page**. This will become the default option when you create a new Article.
> 0 votes

# Answer
To fix this issue edit the content and just you need to unchecked the **promoted to font page** options under **publishing options** tab at the end of edit page.
> 0 votes

---
Tags: nodes
---


# Question
Title: form_state->setRedirect(to_a_new_node_page) from the submitForm function, route "does not exist" issue
I created a custom module, It generate a custom Form in a page. When I submit my form, I create a new node. So, I am redirect to the form page but I would like be redirect to the new node page.

I add this line at the end of my submitForm function :

```
$form_state->setRedirect('node/'.$mynewnode->id());

```

But when I submit my form from the website, I get the empty-white-screen-of-the-death. My apache log :

```
...
Uncaught PHP Exception Symfony\\Component\\Routing\\Exception\\RouteNotFoundException: "Route "node/153" does not exist.
...

```

And then, when I go manually to the node/153 page, there isn't any problem. The page work well.

My question : where is my mistake ? How can I set the redirection after create the new node ? Is it possible from the submitForm function ?

# Answer
> 7 votes
I think if you want to use the setRedirect function then you might want to look at its documentation found https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Form%21FormState.php/function/FormState%3A%3AsetRedirect/8

You can then base the ff. code from FormSubmitter::redirectForm or FormSubmitterInterface::redirectForm. So your code might look something like:

```
$form_state->setRedirect('entity.node.canonical',
  array('node' => $mynewnode->id()),
));

```

You can also find out where is "entity.node.canonical" from by searching in core/modules/node and where it is declared and what it's about.

Hope everything's going great!

---
Tags: 8, redirection, forms
---


# Question
Title: Different css of #main-content at differnt page url?
I have set the css of the main content in theme css as,

`#main-content {
 background:#CCC;
 box-shadow: 0 0 1px #0F4C6A;
}`

So it gets apply to the every page/node/content whatever I create which is quite common. For some pages I do not want this css to apply to `#main-content`. Is there any way I can achieve this?

# Answer
## Option 1 - Pure CSS

For those specific pages you can use the classes found in the `body` tag to override your generic style like so:

```
#main-content { ... }

.page-node-123 #main-content {
  your override for this node
}
.node-type-article #main-content {
  your override again
}

```

## Option 2 - CSS with Drupal coding

Use preprocess hooks like hook\_node\_view or template\_preprocess\_page or hook\_preprocess\_html in the template.php file in your theme and add additional classes based on your specific requirements/conditions

Then use CSS to target those classes or IDs.

Drupal helps us already by default on basic IDs and classes that we need to target things globally or specifically we just need to do an inspect element on the page and check for yourself.
> 2 votes

# Answer
Use can use the body element and this class to apply CSS. Drupal create a unique body class for every page.
> 2 votes

# Answer
If you see body class names then there numbers of class attached with body tag. Out of them one class generated based on node information.
> 1 votes

---
Tags: theming
---


title: How do I use some bootstrap snippets?

text:
# Question
Title: How do I use some bootstrap snippets?
I'm having problem to use markup. based on this snippet code

```
<div class="container">

    <div class="row">
        <div class="col-md-3">
            <div class="thumbnail">
                <div class="caption">
                    <h4>Thumbnail Headline</h4>
                    <p>short thumbnail description</p>
                    <p><a href="" class="label label-danger" rel="tooltip" title="Zoom">Zoom</a>
                    <a href="" class="label label-default" rel="tooltip" title="Download now">Download</a></p>
                </div>
                <img src="http://lorempixel.com/400/300/sports/1/" alt="...">
            </div>
      </div>

    <div class="row">
        <div class="col-md-3">
            <div class="thumbnail">
                <div class="caption">
                    <h4>Thumbnail Headline</h4>
                    <p>short thumbnail description</p>
                    <p><a href="" class="label label-danger" rel="tooltip" title="Zoom">Zoom</a>
                    <a href="" class="label label-default" rel="tooltip" title="Download now">Download</a></p>
                </div>
                <img src="http://lorempixel.com/400/300/sports/2/" alt="...">
            </div>
      </div>

    <div class="row">
        <div class="col-md-3">
            <div class="thumbnail">
                <div class="caption">
                    <h4>Thumbnail Headline</h4>
                    <p>short thumbnail description</p>
                    <p><a href="" class="label label-danger" rel="tooltip" title="Zoom">Zoom</a>
                    <a href="" class="label label-default" rel="tooltip" title="Download now">Download</a></p>
                </div>
                <img src="http://lorempixel.com/400/300/sports/3/" alt="...">
            </div>
      </div>

    <div class="row">
        <div class="col-md-3">
            <div class="thumbnail">
                <div class="caption">
                    <h4>Thumbnail Headline</h4>
                    <p>short thumbnail description</p>
                    <p><a href="" class="label label-danger" rel="tooltip" title="Zoom">Zoom</a>
                    <a href="" class="label label-default" rel="tooltip" title="Download now">Download</a></p>
                </div>
                <img src="http://lorempixel.com/400/300/sports/4/" alt="...">
            </div>
      </div>

  </div>

</div><!-- /.container -->

```

What I did is:

1. Add the CSS code file into my theme folder and insert a line (`stylesheets[all][] = css/custom.css`) in .info file that point to it.
2. Add the js code file into my theme folder and insert a line (`scripts[] = js/custom.js`) in .info file that point to it.
3. Copy and paste the html code into my ckeditor (as a source) block body.
4. Check the Popovers and Tooltips (hover and focus trigger are ticked) option in theme option to make sure they are enabled. Although, I tested and added the following code, but nothing happened.

```
function($) {
  $(function() {
    $(document).tooltip({ selector: '[data-toggle="tooltip"]' });
    $(document).popover({ selector: '[data-toggle="popover"]' });
  });
})(jQuery);

```

I checked the HTML output; the CSS file loaded properly, but in the output I just see the picture and styles, but when I hover over the pictures, nothing happens.

# Answer
> 0 votes
we should put the the js code inside a function like this

```
(function ($) {
$(document).ready(function(){
    $("[rel='tooltip']").tooltip();
    $('.thumbnail').hover(
        function(){
            $(this).find('.caption').slideDown(250); //.fadeIn(250)
        },
        function(){
            $(this).find('.caption').slideUp(250); //.fadeOut(205)
        }
    );
});
}(jQuery));

```

---
Tags: 7, javascript, theming
---


# Question
Title: I can't uninstall modules with Drush master-branch and almost no data on Google
When navigating to my sites' folder and typing `drush pmu admin_menu` or otherwise `drush pm-uninstall admin_menu` in drush master branch I get:

> Command pm-uninstall needs a higher bootstrap level to run - you will need to invoke drush from a more functional Drupal environment to run this command.

I found only 3 discussions in Google, touching this in relation to Drupal 7 (dev or fresh).

* I should note that another command, drush cr (cache-rebuild) works just fine.

## Drush status:

```
C:\wamp\www\sname>drush status
 Drupal version         :  8.0.0
 Site URI               :  http://default
 Database driver        :  mysql
 Database hostname      :  localhost
 Database port          :  3306
 Database username      :  sname
 Database name          :  sname
 PHP executable         :  php.exe
 PHP configuration      :  C:\wamp\bin\php\php5.5.12\php.ini
 PHP OS                 :  WINNT
 Drush script           :  C:\drush-master\drush.php
 Drush version          :  8.1-dev
 Drush temp directory   :  C:\Users\Beni\AppData\Local\Temp
 Drush configuration    :
 Drush alias files      :
 Drupal root            :  C:\wamp\www\sname
 Site path              :  sites/default
 Sync config path       :  sites/default/files/config_mkuaR5uFQ7VCjh1_FFBuZzWXkUsz-sA7Klv4HO_2yLJG33wfJJabdavO7QKzyIRWiQoWA3IJbg/sync

```

C:\wamp\www\sname\>

## Drush sql-conf

```
C:\wamp\www\sname>drush sql-conf
Array
(
[database] => sname
[username] => sname
[prefix] => Array
    (
        [default] =>
    )

[host] => localhost
[port] => 3306
[namespace] => Drupal\Core\Database\Driver\mysql
[driver] => mysql

```

# Answer
The problem is not with Drush is with admin\_menu. This is a bug on admin\_menu not been ready. See more about this - admin\_menu has broken d8-beta11 and i cant pm-uninstall

How to solve it ?

> (note, deleting the module rm -r modules/admin\_menu and rebuilding cache brings the site back)

Source

**Steps by Step Instructions**

* Open your terminal
* Change directory to you root Drupal 8 core
* Then remove the admin\_menu project and then clear the cache.
* `rm -rf modules/admin_menu # Remove the directory.`
* `drush cr # This will clear the cache`

admin\_menu is not ready, I will recommend you to use admin\_toolbar for now.
> 0 votes

---
Tags: drush, 8
---


title: How do I add JavaScript?

text:
# Question
Title: How do I add JavaScript?
I'm creating a website and I want to display a widget from another website inside a block.

In the widget description, I have this information:

> Paste this code at the top of your website code, with the other JS includes. If you are already loading jQuery, please remove it from the code below and only load the widgets.js
>
> ```
> <script async src="https://widgets.nitropanel.com/widgets.js" type="text/javascript"></script>
>
> ```
>
> Paste the following code where you want your widget to appear on your website, note that the widget is 100% width, so you will need to contain it.
>
> ```
>      <div class="nitrous-widget" data-server-id="NN63197376" data-theme="green" data-refresh="10"></div>
>
> ```

How do I include this first code inside the header (or footer)?

# Answer
Your canonical reference for this is here. In short:

1. Save the CSS or JS to a file. (I normally do this at
`docroot/themes/projecttheme_directory/js/`)
2. Define a "library", which can contain both CSS and JS files.
3. "Attach" the library to a render array in a hook.

You can add these files globally, (see **"Attaching to all pages"**) or to specific pages or blocks, (**Attaching a library in a Twig template**) There's a good deal of flexibility in how you can add your javascript, so be sure to review all the options listed there.
> 1 votes

---
Tags: javascript, 8
---


# Question
Title: How to disable user and e-mail input auto-fill?
I'm trying figure out, how I can disable auto-fill or change markup of 'user' and 'e-mail' input forms, when a user is logged in.

This auto-fill feature is breaking my design, because the 'user' and 'e-mail' markup are just a text inside a div and I can't apply a correct style on it.

# Answer
> 1 votes
Something in the core stores user login and drupal use this information in every form submit, in other lines, I can't let user change 'user' and 'e-mail' inputs. BUT, I found how to change markup and correct my design. Follow...

In `'mytemplate'\templates\form\form-element.html.twig` I changed:

```
...[omitted]...

78.   {{children}}

...[omitted]...

```

for:

```
{% if logged_in and element['#type'] == 'item' %}
  <input type="text" name="{{name}}" value="{{element['#value']}}" disabled>
{% else %}
  {{ children }}
{% endif %}

```

And my form now looks like this:

---
Tags: forms, 8
---


# Question
Title: How do I get a list of all CSS and JS that are attached to a page?
In Drupal 8, how do I get all CSS and JS that is attached to a page? In Drupal 7, I could use `drupal_add_css()` or `drupal_add_js()` without arguments, to get an array containing a list of all the files/inline added to a page.

I'm developing a module that will display a "preview" of the block on block configuration page. The method I chose is displaying the block code in a `<iframe>`, but to be properly styled, I need to output all styles with it. This is why I want to read all possible CSS/JS in this "preview" page controller.

# Answer
> 0 votes
You cannot get a list of css/js files because it is constructed very late in the render process.

However, since you want to use an iframe to achieve that goal, you can get it through the normal loading order of a drupal page.

The following is a proof of concept controller method you can use to display a block in a simplified html mode.

```
public function preview($block_id) {
  /** @var BlockInterface $block */
  $block = Block::load($block_id);

  /** @var BareHtmlPageRendererInterface $bare_html_page_renderer */
  $bare_html_page_renderer = \Drupal::service('bare_html_page_renderer');
  $content = [
    'preview-child' => \Drupal::entityTypeManager()->getViewBuilder('block')->view($block)
  ];

  return $bare_html_page_renderer->renderBarePage($content, 'preview-title', 'preview-theme');
}

```

---
Tags: javascript, 8, theming
---


# Question
Title: What is the best way to import new changes from dev to live site using feature module
I have a live site and I have done many new changes on the dev site already.

I would drop the database on live and import the dev DB into it but there are users on live site.

I came across Features module . What will be best way if I:

* create a huge feature with all the options selected (content types, permission, etc etc ) and import it to live site.
* or create many little modules using feature and import them to live.

I don't know what changes I have made to dev. There is lot of work which I can't remember.

# Answer
Do not use a huge feature with all your changes because Drupal may have problems managing it. I recommend to split your configuration in several Features.

If your project is absolutely custom and you are not going to reuse your custom configuration you can create a Feature for every Drupal domain obejct. For example, create a Features for each Content Type, a Feature for the base Fields, a Feature with all your Views, another Feature with the roles, anohter Feature witj all permissions, and so on. If any of those Features becomes too big (for example, you have hundreds of Views) you can just split it into smaller Features.

If your configuration may be reusable in other projects use Features that more or less pacakge a single site feature.

There's no way to know what you have changed from your dev site compared to live site easily. I suggest to just create your Features and deploy them in a clone of your pro site and check everything works ok. If not, trace the missing configuration.
> 1 votes

---
Tags: features
---


# Question
Title: How to set the path for the public directory?
I used to have a Drupal 7 installation on `var/www`, but I had to move it to `var/www/drupal`. The problems is that my files are still in `var/www/sites/default/files` and I am unable to move them.

I need to make Drupal use that directory as default file directory (just on level above). On `admin/config/media/file-system`, I tried to use absolute file path, without success. I tried to set `../sites/default/files` too; it was almost successful, but now I am having problems with the image creation and caching. I have to manually load every single image style; otherwise, it does not find the file.

How can I set up a public file folder which is one folder above Drupal's root folder?

# Answer
You can maybe create a symlink of /var/www/sites/default/files to /var/www/drupal/sites/default/files. Assuming you're inside /var/www/drupal, the command to do that is:

```
ln -s ../sites/default/files sites/default/files

```

So with this in the File System configuration page, you can just use the default path "sites/default/files".

But you can also just transfer /var/www/sites/default/files into it's new and final location though just to make things cleaner and organized, if you want.

## Updated

Since you have noted also that "../sites/default/files" almost worked maybe you just need to update the permissions of the folder to maybe 775 and try to clear caches.

Hope everything works for you.
> 1 votes

# Answer
Change the file path from drupal configuration and the clear the cache and rebuild the registry.
> 0 votes

# Answer
After many hours desperately looking for a solution to override the public file path, I managed to find a better solution.

At `admin/config/media/file-system` changed back to default settings `sites/default/files` and added some extra line in the .htaccess file of drupal's root directory.

```
RewriteEngine on
RewriteRule ^sites/default/files/(.*)$ /sites/default/files/$1 [NC, L]

```

So this perfectly redirects `example.com/drupal/sites/default/files/foo.jpg` to `example.com/sites/default/files/foo.jpg`
> 0 votes

---
Tags: files, configuration
---


# Question
Title: Views - Wrapper Fields in DIV after ROW class
Have this:

```
<div class="ROW CLASS">
      <div class="views-field"></div>
      <div class="views-field"></div>
      <div class="views-field"></div>
      <div class="views-field"></div>
</div>

```

And need this:

```
<div class="ROW CLASS">
   <div class="FIELDS CONTAINER">
          <div class="views-field"></div>
          <div class="views-field"></div>
          <div class="views-field"></div>
          <div class="views-field"></div>
   </div>
</div>

```

# Answer
If you start editing your view, on the right side under the advanced options you will find Theme: information. You will see the currently used template files and the candidate files. My solution would be to overwrite the default template files with your own. That way you could simply add a wrapper around $rows.
> 1 votes

---
Tags: views
---


# Question
Title: What are the alternatives for storing client side encrypted data?
I want to store client side encrypted data in Drupal 7, so that it is encrypted on the client end, and stored and transmitted in encrypted form. The password is never transmitted or stored on the server. The only modules I have found which do this are CSE and Text jQuery Encode RC4 (+CCK) but they are for Drupal 6.

I need something that is user specific, so that different users can use different keys, rather than a single key or a set of keys used on the server end.

Are there any similar modules for Drupal 7?

# Answer
> 4 votes
Personally I would not trust any JavaScript or Flash provided by operator to safely hide my data from him. How can I know if data is really encrypted on my side, or is it just a smoke and mirrors? Probably that's the reason modules like that was never popular - they simply can't be trustworthy, so why to bother developing them if hardly anyone will trust them?

And if user is technological enough to know if data was encrypted on his side or not, he would prefer the other way. There is a way that allows user to be sure their data was encrypted on their side:

1. Make user install FireGPG plugin, or something analogous for his browser, to be able to encrypt any text field with *his* tool, that's under *his* exclusive control, and developed by Open Source teams *not connected* to you.
2. On Drupal side, Field Validation should stop Drupla from saving data that does not look like PGP block. Clientside Validation should stop user from posting it in the first place, but you never know for sure with client-side mechanisms.
3. Secure Pages should mitigate the risk of accidental access to data if user will manage to send unencrypted despite clientside validation.

# Answer
> 2 votes
Not at the moment. However, I'm hoping we can come together as a community and build a module that integrates Drupal with the Crypton JavaScript framework, or something similar.

There's an Encrypt module that's used by Encrypted Files and Field Encryption. I added a feature request for it to support client-side encryption. Let's see if we can work on this and track it over there.

*Update (September 2017): Thanks to GSOC we now have two contrib modules that support this. See the update in https://www.drupal.org/node/2629962 (the feature request) for more information.*

---
Tags: 7, javascript, forms, security
---


# Question
Title: Fatal error: Maximum execution time of 240 seconds exceeded in ...database.inc on line 2171
I have a dilly of a pickle here. Not everytime, but frequently when I load any page Drupal 7 gets all of the contents of the page but then is still loading/spinning. After enough time goes by I get this error below:

```
( ! ) FATAL ERROR: MAXIMUM EXECUTION TIME OF 240 SECONDS EXCEEDED IN C:\WAMP\WWW\PROJECTS\ELAW\INCLUDES\DATABASE\DATABASE.INC ON LINE 2171
CALL STACK
#   TIME    MEMORY  FUNCTION    LOCATION
1   0.0000  245840  {main}( )   ..\index.php:0
2   34.1600 26139624    menu_execute_active_handler( )  ..\index.php:21
3   36.9871 40078664    drupal_deliver_page( )  ..\menu.inc:532
4   36.9871 40080080    drupal_deliver_html_page( ) ..\common.inc:2557
5   37.8472 40875392    drupal_page_footer( )   ..\common.inc:2673
6   38.1012 41024656    system_run_automated_cron( )    ..\common.inc:2700
7   38.1012 41025016    drupal_cron_run( )  ..\system.module:3505
8   40.5573 41112424    module_invoke( )    ..\common.inc:5265
9   40.5573 41112760    call_user_func_array:{C:\wamp\www\projects\elaw\includes\module.inc:866} ( )    ..\module.inc:866
10  40.5573 41112960    search_cron( )  ..\module.inc:866
11  40.5573 41114344    module_invoke( )    ..\search.module:363
12  40.5573 41114688    call_user_func_array:{C:\wamp\www\projects\elaw\includes\module.inc:866} ( )    ..\module.inc:866
13  40.5573 41114888    node_update_index( )    ..\module.inc:866
14  96.6225 42552024    _node_index_node( ) ..\node.module:2767
15  96.9115 43064736    search_index( ) ..\node.module:2798
16  277.8849    43777736    MergeQuery->execute( )  ..\search.module:720
17  277.9279    43789880    InsertQuery_mysql->execute( )   ..\query.inc:1621
18  277.9279    43790816    DatabaseConnection->query( )    ..\query.inc:36
19  277.9289    43793448    DatabaseStatementBase->execute( )   ..\database.inc:683

( ! ) FATAL ERROR: MAXIMUM EXECUTION TIME OF 240 SECONDS EXCEEDED IN C:\WAMP\WWW\PROJECTS\ELAW\INCLUDES\DATABASE\DATABASE.INC ON LINE 2171
CALL STACK
#   TIME    MEMORY  FUNCTION    LOCATION
1   0.0000  245840  {main}( )   ..\index.php:0
2   34.1600 26139624    menu_execute_active_handler( )  ..\index.php:21
3   36.9871 40078664    drupal_deliver_page( )  ..\menu.inc:532
4   36.9871 40080080    drupal_deliver_html_page( ) ..\common.inc:2557
5   37.8472 40875392    drupal_page_footer( )   ..\common.inc:2673
6   38.1012 41024656    system_run_automated_cron( )    ..\common.inc:2700
7   38.1012 41025016    drupal_cron_run( )  ..\system.module:3505
8   40.5573 41112424    module_invoke( )    ..\common.inc:5265
9   40.5573 41112760    call_user_func_array:{C:\wamp\www\projects\elaw\includes\module.inc:866} ( )    ..\module.inc:866
10  40.5573 41112960    search_cron( )  ..\module.inc:866
11  40.5573 41114344    module_invoke( )    ..\search.module:363
12  40.5573 41114688    call_user_func_array:{C:\wamp\www\projects\elaw\includes\module.inc:866} ( )    ..\module.inc:866
13  40.5573 41114888    node_update_index( )    ..\module.inc:866
14  96.6225 42552024    _node_index_node( ) ..\node.module:2767
15  96.9115 43064736    search_index( ) ..\node.module:2798
16  277.8849    43777736    MergeQuery->execute( )  ..\search.module:720
17  277.9279    43789880    InsertQuery_mysql->execute( )   ..\query.inc:1621
18  277.9279    43790816    DatabaseConnection->query( )    ..\query.inc:36
19  277.9289    43793448    DatabaseStatementBase->execute( )   ..\database.inc:683
20  278.2359    43791168    _drupal_shutdown_function( )    ..\bootstrap.inc:0
21  278.4429    43791160    call_user_func_array:{C:\wamp\www\projects\elaw\includes\bootstrap.inc:3454} ( )    ..\bootstrap.inc:3454
22  278.4429    43791536    search_update_totals( ) ..\bootstrap.inc:3454
23  518.0976    43993744    MergeQuery->execute( )  ..\search.module:383
24  518.0986    44004992    UpdateQuery->execute( ) ..\query.inc:1643
25  518.0996    44006664    DatabaseConnection->query( )    ..\query.inc:1177
26  518.0996    44008880    DatabaseStatementBase->execute( )

```

This was a fresh Drupal 7 install that I installed Migrate & Drupal To Drupal Data Migration on and migrated some content from a drupal 6 site, and a drupal 5 site. I started noticing the timeout bug when I installed migrate and migrated the data from drupal 6 (which was done before the drupal 5 content. I am done with migrating now and have even uninstalled/removed Migrate & D2D Data Migration modules.

I also can't run cron. When I try I get "Cron run failed", and in the reports section: "Attempting to re-run cron while it is already running."

Also, when I go to the modules page there is an error listed on top:

I have enough memory and my php timeout is set high. Also I have other Drupal 7 sites running under the same wamp server and they do not have any problems.

Please help me. Thanks!

# Answer
Check for a broken schema with the Schema module.

From the Schema module project page:

> *Schema comparison*: the module compares the live database structure with the schema structure declared by all enabled modules, reporting on any missing or incorrect tables.
> 1 votes

# Answer
To fix this problem I re-migrated all my content and the error just went away.
> 0 votes

# Answer
Your Drupal cron job takes longer to run than 240 s, but its code limits itself to 240 s via `drupal_set_time_limit(240)`. This is done in various other places in Drupal core as well.

Since in your case it's a fresh Drupal install, these cron runtimes seem not justified. But they might be, for example rebuilding the content access permissions did regularly take longer than 240 s in one of my sites with a lot of content. When it succeeds once for your site, it would not be called again during cron runs.

So as a solution, let's assume for now that these cron runtimes are jstified, and disable PHP's maximum execution time for them:

1. Configure Drupal to disable its "automated cron" feature (see here, section 'Disabling "automated cron"').
2. Set up the Drupal cron tasks to be triggered via the system's crontab and drush instead, following these instructions. This will use the PHP CLI interface ("PHP on the command line"), which always has `max_execution_time=0` (unlimited), unlike your webserver.
3. Make sure that Drupal does not self-limit its now unlimited execution time for the cron job to 240 s again. Because,this happens prior to Drupal 7.40 due to Drupal Core issue #2233929. So just make sure you have Drupal 7.40 and it's fine.

Now, Drupal will still call `drupal_set_time_limit(240)` etc. in its code, but since Drupal 7.40 they have no effect anymore if execution time is unlimited as here (see the current source of `drupal_set_time_limit()`).
> 0 votes

---
Tags: 7, cron, migrations
---


# Question
Title: How can a poster of a comment notify selected users about a new comment?
When I write a comment on a node, I want to be able to select the users that will get a notification (via e-mail) about that new comment. Basecamp has this feature and I think it is very cool.

Is this possible without customization? I know how to notify the author of the comment, but this is different.

# Answer
> When I write a comment on a node, I want to be able to select the users that will get a notification about that new comment.

**1)** Download Rules and Entity Reference Modules.

**2)** Enable Rules, **Rules UI** (User Interface, we need this), and Entity Reference

**3)** In your comment fields

* Add a field with **Entity Reference** and a widget of **Auto complete (tag style)**

For example: I named mine lalala (click picture below to enlarge)

**4)** In your field settings:

* Select User as your target type

After you click save field settings you are taken to another screen, scroll down and find **Number of values** and change it to **Unlimited** and Save Changes.

**5)** Add a new rule by going to `/admin/config/workflow/rules/reaction/add`

* React on Event: After Saving New Comment
* Restrict by Type: Select your content type (In this example it's Article Comments, since in Articles Comments is where I put my lalala field.)

**6)** Click on **Add a Loop**

* Data selector: **comment:field-lalala** (remember I named my entity reference field lalala)

**7)** **Click Add Action, but the one from the loop!**

**8)** Select **Fetch Entity by Property**

* Entity Type: User
* Property: Email
* Data Selector: list-item:mail
* Limit Result Count: put a large number here in case it has an effect. (since we are looping, I don't believe so, but I am not 100% sure)

**9)** Add another action to the loop, this time add **Send Mail**

Click on switch to data selection button.

To: **list-item:mail**

## The end result should look like this

## Now add a new comment.

On your entity reference field since we are using Autocomplete (tag style) you start to type a user name and select the user. Then add a comma `,` to add more users

Ex:

### After posting the comment, all referenced users should receive an e-mail.
> 6 votes

# Answer
To my knowledge this is NOT possible only usiing Drupal core, so you'll have to do some "customization". So far the bad news ... The good news is that you can use the Rules module to create a rule to send such notifications.

However the challenge in your question is "which users should get the notifications". If you'd have dozens, or hundreds (or thousands?) of users, using something like a select list doesn't seem like an option to me. Therefor I'd recommend you to use the Flag module to have each user indicate something like "Notify these users whenever I post comments" (using so called "private" flags).

With both Rules and Flag in place, it's a piece of cake to then send notifications of comments that get posted to the users flagged by the author of the comment. To do so, I'd recommend you to also have a look at the Community documentation about the Message Stack, which allows you to do way more then just "sending an eMail".

The previous approach will always send such notifications to the same set of (flagged) users, for each comment posted by a single user. Unless the list of flagged users is adapted before posting a new comment (by flagging more users, or unflagging some previously flagged users). However, by also using the Flag Lists module you could make this more flaxible. I.e. each user can create his/her own set of flags (similar to "Google circles"?). Some more details about Flag Lists (from its project page):

> Flag lists allows regular users to create unlimited private flags called lists. Flag lists extends Flag. In Flag, a site administrator creates the flags that any authorized users may use. In Flag lists, users create their own lists, and they may only add to their own lists.
> 2 votes

---
Tags: 7, comments, notifications
---


# Question
Title: Override module function in my custom module?
I am using module Mixpanel in my site. And I want to override function of this module. Here is link where we can see the function or code which I need to alter CODE NEED TO MODIFIED

Below is the code line which suggest that I can override this function :

```
    // Let other modules alter the defaults.
    drupal_alter('mixpanel_defaults', $properties, $account);

```

So from above line I am trying to override it with code as below, please let me know what I am doing wrong as it does not make any changes. However if I do same thing in main module it make changes but I don't want to make change in module but want to do in my custom module.

My custom module name: **custom**

```
function custom_mixpanel_defaults_alter($properties, $account) {

  $properties['distinct_id'] = $account->name;

}

```

When i see in `system` table weight of my `custom module` is `1000` and weight of `Mixpanel` is `0`.

Please suggest! Thanks

# Answer
The error is how you define the parameters, which should be defined as `custom_mixpanel_defaults_alter(&$properties, $account)`.
PHP 5 automatically passes by reference any object passed to a function, but not the arrays. Since `$properties` is an array, you need to make the reference explicit.

Generally speaking, when you see a call to `drupal_alter()` like `drupal_alter('node_view', $build)`, and you need to implement that alter hook, check the second and third parameter are object or arrays; in the case they are array, you need to explicitly declare the parameter as reference. In this case, `hook_node_view_alter()` is defined as `hook_node_view_alter(&$build)`.
> 2 votes

---
Tags: hooks
---


# Question
Title: Core Search only yielding results on specific words
We've developed a lot of Drupal 7 websites, but never encountered this before (or just didn't notice). When searching the project in question (while having re-indexed the site untill the index is 100%) for a specific word like `met` it finds a basic page node which contains that word, perfect. Though when looking in the same node and trying the word `emissiespectograaf` we cannot find the same node nor any other. This goes for a lot of other words, long or short.

I'm just not getting it, it finds one word in a node but another word, which I know for sure that is in the same node, it's unable to find it. Even though the index has been built for 100%.

# Answer
> 0 votes
Found the culprit after hours of debugging, it seems that the module Features is causing major issues with resetting the Drupal static. See this issue which contains a temporary workaround patch, since this issue has not been resolved with a solid fix yet.

---
Tags: 7, search
---


# Question
Title: User password reset - redirect one time login to another page
By default, if user submit his email in form at `/user/password` page, he will recieve an email with one-time login link. After opening this link he is redirected to page with form with one single "login" button - id of this form is `user_pass_reset`. After click on this button user is redirected to his profile in administrative part of a site: `/user/X/edit` where he can change his password.

But I have my own custom profile page, where users can change their password and I'd like to redirect user here instead of default profile in administration interface. I already found that `user` module is checking if old password is needed with this line:

```
$pass_reset = isset($_SESSION['pass_reset_' . $account->uid]) && isset($_GET['pass-reset-token']) && ($_GET['pass-reset-token'] == $_SESSION['pass_reset_' . $account->uid]);

```

But I can't find out how to redirect user to my own form on `user_pass_reset` submit. If I alter this form and change `'#action'` paramter I get a message that says this one-time login link is invalid. If I add my own submit function `$form['#submit'][] = 'activit_password_redirect';` and in this function I call `drupal_goto('my/own/form/page')` user is still redirected to default profile page.

Is it possible to change url of this form submit?

# Answer
Use hook\_form\_alter, then add a $form\['#redirect'\] parameter with value as your custom user profile page.

OR append a **destination** query to the default form action url.

```
<default_action_url>?destination=<your_custom_user_profile_url>

```

I recommend the first option. It's the Drupal way.
> 1 votes

---
Tags: users, forms
---