# Question
Title: Migration from a remote database PDOException
I'm setting up a database migration. For now, I'm using the ssh tunnel to access the remote databse.

Here is the configuration in the Migration class:

```
<?php
...
Database::addConnectionInfo('for_migration', 'default', array(
  'driver' => 'mysql',
  'database' => 'database',
  'username' => 'user',
  'password' => '****',
  'host' => '127.0.0.1',
  'port' => '1000',
  'prefix' => '',
));

// Conect to the remote $databases
$query = Database::getConnection('default', 'for_migration')
    ->select('Content', 'ct');

// Better descriptions for wineid and name; best_vintages is added in prepareRow()
$source_fields = array(
  'id' => t('article ID'),
  'contenido' => t('Contenido'),
);

// Create a MigrateSource object, which manages retrieving the input data.
// Tell the source class not to try to join the map table.
$this->source = new MigrateSourceSQL($query,
    $source_fields,
    NULL,
    array('map_joinable' => FALSE)
    );

$this->destination = new MigrateDestinationNode('article');

$this->map = new MigrateSQLMap($this->machineName,
    array(
        'id' => array('type' => 'int',
                           'not null' => TRUE,
                           'description' => 'Article ID',
                           'alias' => 'id',
                          ),
        ),
        MigrateDestinationNode::getKeySchema(),
        'for_migration'
    );

// @todo Mapped fields
$this->addFieldMapping('body', 'content');
?>

```

When I try to access the migration UI page the count of items is correct, but I get and error when I try to load the task page to visualize the mappings and elements.

```
DOException: 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 'FROM Content ct LIMIT 1 OFFSET 0' at line 1: SELECT FROM {Content} ct LIMIT 1 OFFSET 0; Array ( ) in MigrateSourceSQL->fields() (line 211 of /Users/brightsitesSM/Sites/devdesktop/independentpoc-dev/docroot/sites/all/modules/migrate/plugins/sources/sql.inc).

```

Probably there is something missing in the code as the `SELECT` in the SQL query is empty.

Here are the screenshots of the migration page:

... and the task page error:

# Answer
> 0 votes
The problem with the code is the connection to the database. There aren't fields in the select.

```
SELECT FROM {Content} ct

```

To solve that one of the solutions is adding `->fields('ct');` to the database connection. This will select all the fields from the table ct:

```
SELECT ct.* FROM {Content} ct

```

---
Tags: migrations, database
---


# Question
Title: When programmatically adding conditional element to webform, I get errors
I'm trying to add a new conditional attribute to a bunch of webforms using a script. There are already 12 conditions, and I need to add a 13th one.

My code looks like this in a basic script module which has $node available:

```
if(stuff_is_true){
 $new_component = array(
  'nid' => $node->nid,
  'rgid' => '13',
  'andor' => NULL,
  'action' => 'hide',
  'target_type' => 'component',
  'target' => '22',
  'weight' => '13',
  'rules' => array(
    '0' => array(
      'nid' => $node->nid,
      'rgid' => '13',
      'rid' => '0',
      'source_type' => 'component',
      'source' => '21',
      'operator' => 'equal',
      'value' => '0',
    ),
  ),
);

$node->webform['conditionals'][] = $new_component;

// Save the changes
node_save($node);

```

All of this works if put into a hook\_node\_view() (without doing a node\_save obviously), so I know it's structured properly.

The problem comes during node\_save($node) which throws an error like:

```
Duplicate entry '3033-0' for key 'PRIMARY': INSERT INTO {webform_conditional}...

```

(3033 is the nid, and the 0 is the rgid key).

Basically, what it's doing (I think) is trying to re-submit the whole $node-\>webform\['conditionals'\] array as NEW data, so existing components hit this "duplicate primary key" error (because they already exist).

How can I tell node\_save to only ADD my new conditional item to the end of the existing array instead of trying to re-insert the whole thing?

# Answer
It seems as if there's really no clean way to do this. What I realized is that it was easier to just remove all existing conditions, and then re-add them all with the additional condition included. So I started by setting:

```
$node->webform['conditionals'] = array(); //remove all conditions
node_save($node); //save the node, removing all old conditions
$node->webform['conditionals'] = $new_array_of_conditions; //add entire new array of condtions
node_save($node); //save the node with new conditions

```

This doesn't break anything on old nodes because no data or anything else is reliant upon conditions...so removing them doesn't hurt anything or lose any crucial data.
> 0 votes

---
Tags: webforms, nodes
---


# Question
Title: Drush crashes Call to undefined function ctype_alnum() in ubuntu
I've installed drush on ubuntu 14.04 apparently successfully but attempting to use drush within my drupal 7 app yields this:

PHP Fatal error: Call to undefined function ctype\_alnum() in /home/sam/.phpbrew/php/php-5.4.34/lib/php/drush/includes/command.inc on line 896

OK, I'm still new at PHP but apparently my php 5.4.34 installed via phpbrew is calling it? From reading about this function on PHP I see that it's part of PHP 5.4. That said, it does not show up in my phpinfo() page. Looking around the web the few times I see this as an issue seems an issue with certain modules. My code using the drush installed on OS X shows no problems so perhaps it's not my code?

Ubuntu didn't seem to report errors on install and I'm not sure if I need to install some extension to my php or if there's something wrong with my code. Help me see where I need to fix this? thx, sam

# Answer
PHPBrew must be disabling ctype by default.

Try explicitly installing the extension with `phpbrew ext install ctype`
> 0 votes

---
Tags: drush
---


# Question
Title: How to use a custom block template when the block is embedded in a panel pane?
I have a block that I have templated and want to use in and out of a panel layout in various parts of my site.

So to template the block I opted to install the block\_machine\_name module which gives a good anchor point for the template so the block id is not relied upon (as this changes between my dev and prod sites).

Then I theme the block and it works just great using a template name like block--sweet-name.tpl.php

Then I also use the block in a panels layout and things start to go wrong. The block template is now ignored.

So I am trying to find a way to get panels embedded block to respect block templates.

Is this possible?

# Answer
If you need to use the block template in panels, make sure you choose the style from the panels option to be "Systems block".

This lets you use block--sweet-name.tpl.php.
> 3 votes

# Answer
If you have machine name based block templates and you need to also use non machine name block templates as in this example then you can just make a non machine name block template that includes the machine name one. Though still not ideal it could.

```
<?php
    //use the mchine name block
    $path = drupal_get_path('theme', 'myTheme');
    include($path."/templates/block--sweet-name.tpl.php");
?>

```

If anyone has a better solution though I am all ears.
> 0 votes

# Answer
I suggest trying this little backport from Drupal 8. https://www.drupal.org/node/2307505

It will show you all the templates and their suggestions which surround the output of your block. And in this case, it will likely be a pane template.

```
<!-- FILE NAME SUGGESTIONS:
   * panels-pane--block--sweet-module-sweet-name.tpl.php
   * panels-pane--block.tpl.php
   x panels-pane.tpl.php
-->

```
> 0 votes

---
Tags: 7, theming, blocks, panels
---


# Question
Title: Computed field that displays the full username of the author
I am using a computed field and I want to display the field\_first\_name and field\_last\_name, which are properties of the user that created that node.

I have been trying things, but it seems like $entity does not have a uid?

I have no idea how to get load the user. These are the variables I have:

> The variables available to your code include: &$entity\_field, $entity\_type, $entity, $field, $instance, $langcode, and $items. To set the value of the field, set $entity\_field\[0\]\['value'\]. For multi-value computed fields continue with $entity\_field\[1\]\['value'\]. Here's a simple example which sets the computed field's value to the value of the sum of the number fields (field\_a and field\_b) in a node entity: $entity\_field\[0\]\['value'\] = array\_pop(array\_pop(field\_get\_items($entity\_type, $entity, 'field\_a'))) + array\_pop(array\_pop(field\_get\_items($entity\_type, $entity, 'field\_b'))); The first pop fetches the last (or only) item from the field while the second pop fetches its \['value'\] contents (assuming it's the only key that's set).

# Answer
> 0 votes
Not 100% clear what your use case is, but it's possible that the realname module will do exactly what you're after https://www.drupal.org/project/realname

under /admin/config/people/realname enter tokens for the fields you want eg \[user:field\_profile\_first\_name\] \[user:field\_profile\_last\_name\] then whenever the username gets printed it will display these fields instead

# Answer
> 0 votes
Solved it.

```
$uid = $entity->uid;  // Grab the author of the node (this is a profile-type node)
$user = user_load($uid);  // Load the user object, based on user id
$first = $user->field_first_name['und']['0']['value'];
$last = $user->field_last_name['und']['0']['value'];

$entity_field[0]['value'] = $first." ".$last;

```

---
Tags: entities
---


title: uploaded files and images not showing

text:
# Question
Title: uploaded files and images not showing
When i upload a file, be it a avatar picture or image, the file loads however does not display.

I have checked the permissions on my hosting environment and it seems that everye uploaded file gets a 664 permission and apache as owner.

How can i give the uploaded files the proper permission automatically?

# Answer
> 1 votes
To fix the files permission, your folders and files needs to be readable and writable by Apache user.

Example commands to fix your permissions (assuming `www-data` is your Apache user, prefix with `sudo` if required):

```
chgrp -vR www-data "$(drush dd %files)" "$(drush dd %private)"
chmod -vR ug+rwX "$(drush dd %files)" "$(drush dd %private)"

```

You need to have `drush` command available. If you don't have `drush`, just replace above sub-commands in double-quotes with proper locations to your `%files` and `%private` folders.

Then as Drupal admin go to *Reports -\> Status Report* and check for file-system related warnings.

# Answer
> 0 votes
664 should be sufficient to view the image.

However Drupal's image module creates different versions of uploaded images.

It needs to be able to write them into the files directory and create new directories, so your files directory (or at least the 'styles' directory within it) wants 755 permissions recursively (`chmod -R 755 sites/default/files/styles`)

---
Tags: media, files
---


# Question
Title: Why are non-standard file extension used for PHP files?
Is there any reason why Drupal decided to use non-standard file extensions, for example node.install, node.module, simple.profile, case.test? Why doesn't Drupal use .php as extension for PHP files?

# Answer
> 2 votes
Because it's easier for the core to know about special files that way.

As a developer you're free to name your module or theme whatever you like, so that means that Drupal core needs another way to find and identify certain important files. Doing this using the file extension is an easy way.

---
Tags: coding-standards
---


# Question
Title: Remove comma from unlimited items body in content type
i have a content type with multiple body fields. It's works but there is a single comma between the body fields on the rendered page. I can't for the life of me figure out how to remove that god forsaken comma. Pls help!!!

Edit, here is an image to hopefully clarify the output issue I am having:

So, the body is an array:

I need to figure where the array is being rendered so that I can remove the comma that is being used to separate the array.

# Answer
> 1 votes
for anyone else using the progressive theme:

template.php, line 458:

# from

```
  $output .= drupal_render($variables['items'][$i]) . (($i == count($variables['items']) - 1) ? '' : ', ');

```

# to

```
  $output .= drupal_render($variables['items'][$i]) . (($i == count($variables['items']) - 1) ? '' : '');

```

---
Tags: nodes
---


# Question
Title: Git-like way of updating Drupal database
It's easy to update Drupal on the local / remote server using Git.

However, sometimes when I make modifications in the actual module settings or any other settings on my local server – those are recorded in a database and I can't then update them easily on the remote server.

At the moment I just export the whole Drupal database and then overwrite it on the remote server.

But is there any faster / easier Git-like way of doing that?

Maybe a special module? Or a special git-like service for Drupal databases / MySQL databases?

Thank you!

# Answer
> 3 votes
The Configuration module is also a way to store configuration in files rather then the DB. You can then sync configurations by importing the configurations to a new system and pressing a button in the admin area to `sync configuration` with the newly updated files. there also exists a Drush command to invoke the update.

> The configuration management module enables the ability to keep track of specific configurations on a Drupal site, provides the ability to move these configurations between different environments (local, dev, qa, prod), and also move configurations between completely different sites (migrate configurations) without the use of modules with all configuration being owned by the site.

I prefer this approach over Features currently, as this way Features does not attempt to take ownership of any of my files -- or rather become a dependency in my system. I believe you can later uninstall the Configuration module for example and not loose your set configuration values.

# Answer
> 2 votes
Have a look at the Features module. The module allows you to save configuration values to code which you can use and enable on the production site. There are plenty of other possibilities how you can save configuration values to code or run from code. It would be a bit too much to tell you everything. But as a start check features and in addition the module Strongarm. There are other modules (cTools exportables for example) which offer you similar possibilities. But with the two mentions here, you can already cover a lot. Another idea to make configurations on a production site without clicking around is to use a custom module and the hook\_update\_N hook.

Please come back if you have more specific questions.

And last, you should never ever overwrite a production database. Once up and running, it should stay the same (imho).

# Answer
> 1 votes
You can try to put as much of your configuration in code instead of putting it in the database. I don't know of an out of the box solution that is working based on what you ask. For your own modules you could use this hook https://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook\_update\_N/7 when you change stuff around. This way you can update your DB. It isn't ideal of course.

BTW: Thank god Drupal 8 will fix this problem! So it's just a matter of time before we have full configuration in code that can be version controlled.

---
Tags: database
---


title: Custom layouts for responsive site page

text:
# Question
Title: Custom layouts for responsive site page
We're converting a site to be responsive and have decided to use Adaptive Theme. But the client insists on a unique layout for the Front page that does not fit into Adaptive's method of stacking sidebars. In principle I need a layout program like Panels or Display Suite that lets you create two layouts, and then decides which one to use depending on the device. I'm a coder and can do this myself with a page callback, or I suppose in the front page template, but was hoping for another solution. Is there a better way?

# Answer
> 1 votes
I think the theme key module might be just what you need. From the module's page:

> ThemeKey allows you to define simple or sophisticated theme-switching rules which allow automatic selection of a theme depending on current path, taxonomy terms, language, node-type, and many, many other properties. It can also be easily extended to support additional properties exposed by other modules. In combination with Drupal's theme inheritance you can easily achieve features like:

* individually-styled channels
* a front-page / "splash" screen a
* date/time-selected Christmas
* theme mobile themes for different auto-detected mobile devices
* special themes for "limited" or "old" browsers
* content, user, or role -specific themes indicating your
* environment (production, staging, testing, sandbox, … ) testing your
* redesign safely on a live server

And many more. https://www.drupal.org/project/themekey

---
Tags: theming
---


title: Malicious Code - Website Disable

text:
# Question
Title: Malicious Code - Website Disable
I'm new to Drupal. My website has been disable due to malicious code found in **/var/www/vhosts/domain.com/httpdocs/sites/all/themes/tao/tao/css.php**

What should I remove in this file? http://pastebin.com/4xQixw13

# Answer
You should remove the entire file.

Also, this is not enough to fix your site. I would recommend exporting your content and doing a fresh install, with a fully updated version of Drupal.
> 1 votes

# Answer
Remove the file, but more importantly ask yourself how could that file have gotten there.

The Tao theme is a well known public theme so I doubt it came with this code in it, which mean that some system on your server that can write to protected, non-public folders put this file there.

You need to heal the server before you do a re-install or after a certain period of time the same code will get injected again.

You need a program to help you find the bad actors here. Try ClamAV to search your server. Hopefully it will find little but you need to face the possibility that you may need help for you hosting company or a nerdy friend.

Here is a how to article for Ubuntu https://askubuntu.com/questions/250290/how-do-i-scan-for-viruses-with-clamav

Good luck. This happened to me as well, it can be hard but you'll get past it. Learning to run a secure server is an important part of being on the web.

Here is a little more reading to help. https://www.drupal.org/security/secure-configuration
> 0 votes

---
Tags: security
---


# Question
Title: Run a Drupal website offline (±without server)? --- E.g. hand it over on a usb-stick / by mail? --- Run it from the HD, while retaining functionality?
# Why run Drupal offline?

Since I use free webhosting, I don't have 100% up-time, so I started wondering whether I could maintain such Drupal functionality, while at the same time working offline.

# An example of an application

* In general, I am talking about a more or less operational website here.

E.g., my own quest at the moment: I want to let people fill in a couple of words/lines on a Drupal website by clicking on hyperlinks at specific points in a HTML article which is created on a Drupal website - and have the input of the people saved somewhere. *(I still have to find the right module / way of achieving this by the way)*

---

# 1 small step to think, 1 giant leap in technology?

Any thoughts on how to go about this? Perhaps letting people "run" / temporarily host the website from their own computers? (P.S.: I would rather like to keep things as WYSIWYG as possible.)

I am not experienced in this matter, but what do you think would be perhaps missing to pull this off: the handling or online hosting of a MySQL-database; something that has to do with PHP;...?

# Answer
> 0 votes
Drupal is too large a project to be run on slim architecture or dumb terminals. If you're going to buy a USB stick (memory) to store Drupal then buy a "computer stick" and run Drupal off of Sqlite on the stick, for example a Gumstix product with Ubuntu on it $200 USD is hardly more expensive then an expensive large USB memory stick. https://store.gumstix.com/index.php/products/283/

---
Tags: 7
---


# Question
Title: Updating Drush to newer version on Drupalpro VM Virtual Machine Instance
I'm setting up a new vm box with a fresh copy of Drupalpro and I need to update Drush and I'm not sure how to go about it. Any ideas would be great. The current drush version that is preinstalled is 5.3 drush.

# Answer
> 0 votes
Using a fresh setup of Drupal Pro VM image, all you have to do is just goto the drush directory and do a git pull from there to pull in the latest code from drush's repo. This is what i did:

cd ~/drush

git pull

git checkout 7.x-5.9

You can load up another drush version by just listing out the ones available by doing a **git tag**

---
Tags: drush
---


# Question
Title: What does this note for the Autoaave module mean?
I want to install the Autosave module. The project page shows the following note.

> Autosave uses a modified version of the jquery.field plugin (modified since it doesn't support Drupal field naming conventions very well). This version of the plugin was based on jquery 1.2 and does not work with jquery 1.3. Rev 6.x-2.7 DOES support jquery 1.3 and should still support jq 1.2. Please raise an issue if you find that it doesn't.

Can someone please clarify it for me in more simple words?

I wonder if it could clash with other modules that use jQuery.

# Answer
Let's break the question down into parts.

> Autosave uses a modified version of the jquery.field plugin (modified since it doesn't support Drupal field naming conventions very well)

This means that when the project was written, they took a plugin (piece of code) from another module and used it as a base for their own code.

> This version of the plugin was based on jquery 1.2 and does not work with jquery 1.3.

This bit taken just by itself means that the module will not work if you are using JQuery 1.3 or higher with your Drupal site. It does, however look like old information and should be disregarded because:

> Rev 6.x-2.7 DOES support jquery 1.3 and should still support jq 1.2. Please raise an issue if you find that it doesn't.

...which states that version 6.x-2.7 supports JQuery 1.3.

The module has been updated several times since then, as you can see the Drupal 6 module is now on version 6.x-2.11. It is likely that the Drupal 7 version of the module supports much more recent versions of JQuery since it was last updated 6 months after the last Drupal 6 version.

What should you do?

1. Make a development copy of your site if you haven't already, where you can break things without worry. Use a VirtualBox or similar if you know how or can learn.
2. Install the current version of the module and see if it works. Click around your site and see if you can find any unexpected behaviour
3. If it doesn't work, consider installing JQuery Update which allows you to choose the version of JQuery being used by your site.
> 2 votes

---
Tags: javascript
---


# Question
Title: How to alter price in checkout page and when submit order
I have a discount price for product. I want alter price of product using discount price if user has voucher. How to alter price of page cart, cart/checkout and when user submit order. Please help me!

# Answer
> 0 votes
You could use a HOOK for your needs, just read a little bit about hooks, and then create a hook for your content type and change that price.

You can check here how to first create a module and then a hook

Hooks in drupal tutorial

---
Tags: ubercart, commerce
---


# Question
Title: How to export and import from View in Drupal7?
i have a view in my project. And i want to import and export the views in Excel format. How to achieve this?

# Answer
> 1 votes
You can use views data export module.

> This module is designed to provide a way to export large amounts of data from views. It provides a display plugin that can rendered progressively in a batch. Style plugins are included that support exporting in the following types:
>
> ```
> CSV
> Microsoft XLS
> Microsoft DOC
> Basic TXT
> XML.
>
> ```

---
Tags: views, importing-exporting
---


title: How do I download a sandbox project?

text:
# Question
Title: How do I download a sandbox project?
I want to develop the recommendation platform for job orders. In drupal there is the Prediction IO module but it is a sandbox project. How can I download it?

# Answer
As reported in Installing sandbox projects, sandbox projects don't have download links, since versions are not enabled for them. You need to use git to download the code.

Assuming you mean the PredictionIO module, that doesn't still have code, at the moment; it is reported in its Version control tab.

> No code is available for PredictionIO. File an issue or contact a maintainer if you have questions.

If there were code, you could download it with the following command.

```
git clone --branch master http://git.drupal.org/sandbox/mrded/2116851.git predictionio

```

In the *predictionio* directory, you would find the module code.

### Update

On June 17, 2015, the maintainer answered to Code? saying:

> Hi guys,
>
> We actually stopped developing of this module. If you're interested, I can publish your codebase as full project and give you a maintainer permissions to fully control the module.

If nobody is going to offer to be maintainer of that sandbox project, the project will not have any code.
> 4 votes

---
Tags: community-official-site
---


# Question
Title: How to trim a field that's been excluded from display?
In Views, in order to group certain fields inside a common div, i excluded them from display and inserted them in a global text field by using their 'replacement pattern references'.

Here's what the div looks like :

```
<div class="nodetitle">[title]</div>
<div class="date-author"><span>[name]</span> - <span>[created]</span></div>
<div class="readmore"><a href="[path]">More details »</a></div>

```

The thing is i wanted to trim the node title to 50 characters max. Trimming works fine when displaying the field 'as is' but not when it's been used as a replacement pattern in a different field.

Any help on how to achieve this ?

Thanks

# Answer
I've double checked your problem and it seems to works like a charm.

1. In your view go to Field -\> Title -\> \[edit\] -\> Rewrite results -\> Trim this field to a maximum length -\> set maximum length to 50
2. Add Global: Custom text field and place \[title\] in text field.

Result should looks like this:
> 3 votes

---
Tags: 7, entities
---


# Question
Title: Stay with 7.19 or hack 7.22 (to avoid the "itok" issue)
First things first, I don't need a DDoS prevention mechanism in Drupal since that is my server's job.

In all my Drupal installs, I usually hide the identity of Drupal for security reasons. Image style token (itok) is also a Drupal identifier. I tried a hack to remove `itok` in 7.22, and found out `itok` is not a small implementation, which may need more work to get benefit from the community after hack.

I'm just wondering if there is a better way.

# Answer
> 11 votes
No need to hack, just add the following line to your settings.php file:

```
$conf['image_allow_insecure_derivatives'] = TRUE;

```

Source

That will stop the `itok` parameter from being used.

It's even been wrapped in a module if you don't fancy editing settings.php.

Image Allow Insecure Derivatives

> Provides a user interface to allow Drupal to bypass the token security check when generating image derivatives.

As a side note, trying to hide your site's identity as being a 'Drupal' site is pointless. It's known in the field as 'Security through Obscurity', and it's a waste of resources that could be spent solving *real* security or performance issues.

See How can I obscure what I am using to run my site? for a more in-depth explanation.

# Answer
> 2 votes
This problem is in the queue already. Good thing, it's marked critical. Bad thing, it got moved from 7.x to 8.x (with "needs backport" tag but anyway).

Between 7.19 there were many small, beneficial changes. If you can, just hack out itok and upgrade. And if you can make itok configurable, post your patch to the Issue queue I linked.

# Answer
> 1 votes
As far as I can tell `$conf['image_allow_insecure_derivatives'] = TRUE;` doesn't work. At least not on versions 7.26+

So yes, a hack seems like the solution. This worked for me: https://drupal.org/node/1934498

# Answer
> 0 votes
Using ImageMagick instead for GD solves the issue.

---
Tags: 7, tokens, media
---


# Question
Title: How can I include a list of what a user ordered (the line items) in an e-mail sent by Drupal Commerce?
I want to send an e-mail that contains the content of a user's Drupal Commerce order (the line items) with Rules.

I tried modifying the default **Send an order notification e-mail** (in Rules) provided by Commerce. I noticed that there was a `[commerce-order:commerce_line_items]` token, but when I insert this into an e-mail, I get a message of *No line items found* when the e-mail is sent, even though the order has line items. What am I doing wrong?

# Answer
The `[commerce-order:commerce_line_items]` token does not work when *Completing the checkout process*, which is the event for which the **Send an order notification e-mail** rule is triggered.

Instead, one way to do this is to use the Commerce E-mail module, which provides a `[commerce-order:commerce-email-order-items]` token and a new interface for editing the e-mail. Note that you will need to disable the e-mail-sending rule when using this module (or else you will get duplicate e-mails, as the module help points out).
> 3 votes

# Answer
If you are using the Message module together with Commerce Message and Message Notify, another way of doing this would be to simply use the token `!order-summary` in the `commerce_order_order_confirmation` message type provided by the module Commerce Message.

All you have to do is edit the message type at the following URL and add the token in the corresponding field:

```
admin/structure/messages/manage/commerce_order_order_confirmation

```

The rule `Commerce order message: order notification e-mail` will then send an e-mail after checkout is completed which will include the line items.
> 0 votes

---
Tags: commerce, rules, emails
---


# Question
Title: How can I invoke a drush hook on a remote alias?
I have a local dev environment and a test server environment. Both are running the exact same code.

In a custom module, I added a drush hook to extend the *sql\_sanitize* command in order to ensure all private user data is removed from the development database.

From a directory within my local environment, I can invoke drush like this:

> drush sql-sanitize

And my custom drush hook is run properly.

However, when I invoke drush from the same location but targeting my remote server environment (Pantheon, if it matters, and I checked their documentation, but didn't see any relevant notes):

> drush @mytestserver sql-sanitize

*sql-sanitize* resolves, but the custom drush hook is not called, even though the module containing the hook is enabled locally and on the test server.

I tried invoking the command from a directory outside my local dev environment, but again *sql-sanitize* resolved without the custom drush hook being called.

How can I execute the drush hook in a remote environment from my local machine?

I have tried both Drush 5.9 and 6.4.0.

# Answer
I eventually "solved" this by moving the SQL into `myfile.sql` and running it like this:

\`drush @myalias sql-connect\` \< myfile.sql
> 0 votes

# Answer
If I understood correctly, we had a similar problem with drush \< 6.4, drush was not passing the alias to the remote server if `root` and `uri` where not specified.

One way to solve it is to define `$conf['root']` and `$conf['uri']` in your local alias, the other is to use drush 7.
> 0 votes

---
Tags: drush
---


# Question
Title: Rendering renderable arrays in an item_list
I'm struggling to get a render-array constructed, and I think it's because of how `theme_item_list` works. I would be grateful if anyone could help find the problem (or tell me to implement it without item\_list!)

> The context: This function is called from my module's `hook_block_view()` to render the content of the block. The module is an example module showing how to use a new API. I hope nothing of that is needed to answer this point, except that these calls are not made from a theme.

The code I have is:

```
function example_render() {
  $block = array();

/* fill $providers[] ... */

  $items = array();
  foreach ($providers as $metric => $provider) {
    $value = $provider['value'];
    $class_link = $provider['name'];
    $name_link = $provider['name'];

    // Construct a renderable array wrapper for the template invocation.
    $items[$metric] = array(
      '#type' => 'container',
      '#attributes' => array('class' => array('provider')),
      'info' => array(
        'providername' => array(
          '#prefix' => '<span class="provider-name">',
          '#markup' => $name_link,
          '#suffix' => '</span>',
        ),
        'providervalue' => array(
          '#prefix' => '<span class="metric-value">',
          '#markup' => $value,
          '#suffix' => '</span>',
        ),
        'metricname' => array(
          '#prefix' => '<span class="metric-name">',
          '#markup' => $class_link,
          '#suffix' => '</span>',
        ),
      ),
    );
  }

  // Finally, bring it all together.. a container with the via text then a list
  // of the providers.
  $block['content'] = array(
    '#type' => 'container',
    '#attributes' => array('class' => array('example')),
    'ttl_text' => array(
      '#prefix' => '<h3 class="metrics-title">',
      '#markup' => $record['title'],
      '#suffix' => '</h3>',
    ),
    'via_text' => array(
      '#prefix' => '<span class="metrics-via">',
      '#markup' => $via_text,
      '#suffix' => '</span>',
    ),
    'metrics' => array(
      '#items' => $items,
      '#theme' => 'item_list',
      '#attributes' => array(
        'class' => 'providers-list',
      ),
    ),
  );
  return $block;
}

```

and this is what I get when run with 9 items in the list:

```
<div class="example"><h3 class="metrics-title">A bacterial sulfonolipid triggers multicellular development in the closest living relatives of animals</h3><span class="metrics-via">via <a href="http://alm.svr.elifesciences.org/articles/info:doi/10.7554/eLife.00013" external="1" target="_blank">Lagotto article information</a> courtesy of <a href="http://articlemetrics.github.io/" external="1" target="_blank">Lagotto</a></span><div class="item-list"><ul class="providers-list"><li #type="container" #attributes="Array" info="Array Array Array" class="first"></li>
<li #type="container" #attributes="Array" info="Array Array Array"></li>
<li #type="container" #attributes="Array" info="Array Array Array"></li>
<li #type="container" #attributes="Array" info="Array Array Array"></li>
<li #type="container" #attributes="Array" info="Array Array Array"></li>
<li #type="container" #attributes="Array" info="Array Array Array"></li>
<li #type="container" #attributes="Array" info="Array Array Array"></li>
<li #type="container" #attributes="Array" info="Array Array Array"></li>
<li #type="container" #attributes="Array" info="Array Array Array" class="last"></li>
</ul></div></div>

```

not very inspiring!

The three 'Array' under 'info' in the html here obviously correspond to the providername/providervalue/metricname arrays in the code i.e. the $items array isn't being interpreted as a render array at all.

How can I make this work?

# Answer
According to https://api.drupal.org/api/drupal/includes!theme.inc/function/theme\_item\_list/7 theme\_item\_list is looking for `data` key so your list item should look like this:

```
// Construct a renderable array wrapper for the template invocation.
$tmp = array(
  '#type' => 'container',
  '#attributes' => array('class' => array('provider')),
  'providername' => array(
    '#prefix' => '<span class="provider-name">',
    '#type' => 'markup',
    '#markup' => $name_link,
    '#suffix' => '</span>',
  ),
  'providervalue' => array(
    '#prefix' => '<span class="metric-value">',
    '#type' => 'markup',
    '#markup' => $value,
    '#suffix' => '</span>',
  ),
  'metricname' => array(
    '#prefix' => '<span class="metric-name">',
    '#type' => 'markup',
    '#markup' => $class_link,
    '#suffix' => '</span>',
  ),
);
$items[$metric]['data'] = drupal_render($tmp);

```

That should give you single element:

`<li class="first"><div class="provider"><span class="provider-name">test1</span><span class="metric-value">test1</span><span class="metric-name">test1</span></div></li>`
> 3 votes

---
Tags: 7, theming
---


# Question
Title: Can two admins edit the same node content at the same time from different computers?
1. Can 2 admins edit the same node content at the same time from different computers?
2. Can 2 admins edit different node contents at the same time from different computers?
3. Can 2 admins edit a Drupal site at the same time from different computers?

# Answer
Using Drupal core, two users editing the same node concurrently would cause a conflict; the second user would get an error ("This content has been modified by another user, changes cannot be saved."). This would only happen on `node_save()`, once they have submitted the form. A more user friendly option would be to use a module like the Content lock module which highlights an active edit of a node and locks it for others.

Any number of editors are supported on a site simultaneously; the only limitation is editing the same node (and server resources).
> 2 votes

---
Tags: nodes
---


# Question
Title: Site re-directs to login page even after a successfull login
Presently I am using the Windows Server on which the drupal 7.34 is installed with the xampp server.

The url for the site is `localhost:8081/example`

When I enter the URL(`localohost:8081/example`) to login, the page simply re-directs to the login page

Whereas when I enter the complete URL (the IP address along with the port number it loads the site)

Now I can't figure out why the page is redirecting me to the login page but not the main page when I am entering the `localhost:portno/example`

\[update\]

Things Tried:-

1.Pinged the IP address and it was successful with no loss.

2.Tried it on a different browser Internet explorer got Error HTTP Error 403 Forbidden.

3.Tried on a different system with the same IP address and in that system the site loads fine.

4. Re-installed the drupal software again with the same localhost:portno/

# Answer
This behavior is normal

The default front page of Drupal is this one. It displays the latest published and promoted nodes. If you want to put another node as a front page you can do it in configuration\>site information

Also drupal assumes that your site is in the top level directory (e.g. yourserver:port/) If you want to change it to yourserver:port/custompath/ then set the $base\_url to custompath in your settings.php file
> 0 votes

---
Tags: uri, redirection
---


# Question
Title: Is there a way to delete/purge all generated image style images without re-generating them?
I'd like to delete all generated image style images without re-generating them immediately. I want to do this in order to remove them from my backups, because as the number of files on the site increases, it's taking up an exceedingly large amount of space.

I also have the option of making the backup script more complicated and not backing up those directories, but I was wondering if there is a quick way just to remove the generated files only.

# Answer
> 1 votes
You just have to do `drush image-flush --all`. Source : http://www.drushcommands.com/drush-6x/image/image-flush

Examples of using the `drush image-flush` command:

1. `drush image-flush` \- Pick an image style and then delete its images.
2. `drush image-flush thumbnail` \- 'Delete all thumbnail images.
3. `drush image-flush --all` \- 'Flush all derived images. They will be regenerated on the fly.'

---
Tags: media
---


title: Custom views sort handler

text:
# Question
Title: Custom views sort handler
There is a content type has a Field Collection type field(multi value), this Field Collection has a date field, I want to sort the node according to the max date value in this Field Collection field(multi value) in views, how to custom this views sort handler.

# Answer
Use aggregate and set the option for distinct results. Aggregate is similar to GROUP BY in SQL so be careful what fields you include. If you really need to do it with custom code set a tag for your view's query in advanced settings and then use this tag to alter your query by implementing hook\_query\_alter or hook\_query\_TAG\_alter in a custom module https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook\_query\_TAG\_alter/7
> 1 votes

---
Tags: views
---


title: admin menu item not displaying

text:
# Question
Title: admin menu item not displaying
I am developing a module which has an admin menu entry in Drupal 7. The issue I am having is that the menu item is not showing up in the admin menu. I have looked at the docs and scoured google for why this might be happening but nothing I try seems to work.

Here is my hook\_menu() implementation:

```
$items['admin/config/people/accomplishments'] = array(
  'title'            => 'Accomplishments',
  'description'      => 'Configure the accomplishments system.',
  'page callback'    => 'drupal_get_form',
  'page arguments'   => array('accomplishments_admin_form'),
  'access arguments' => array('administer site configuration'),
  'file'             => 'accomplishments.admin.inc',
  'type'             => MENU_LOCAL_TASK,
);

```

I have tried flushing the cache and reinstalling the module but nothing works. I do notice that when I specifically go to the url admin/config/people/accomplishments I get a permission denied error - which doesn't make sense to me as I am logged in as user 1 and I have assigned access privileges to the administrator role.

The module I am developing is creating a new entity so I don't know if this might have a baring on this as I have never created an entity before, but I don't think it should.

Any ideas as to what I am overlooking or what the cause might be? I am going crazy here.

# Answer
> 0 votes
It seems that the path your using is "admin/config/people/accomplishments" Make sure that the users that need to have access to this menu item have sufficient permissions in administering people or use another path

Last make sure you flushed the drupal caches so the changes are applied. Drupal only calculates the menu items once and then it caches them

---
Tags: 7, routes
---


# Question
Title: Content Access exclusive permissions per node
I'm playing around with content\_access module, and I have a question. For my use-case, I need particular nodes to limit editing by role. This means that the content type will allow role\_x to edit by default, but a particular node of that content type will not.

The way it's behaving is inclusive from the top down? If the role has permission on the content type, then they have permission on all nodes of that content type. It's only editable on the individual nodes if they DON'T have that particular permission.

Can someone tell me for sure if that's the proper behavior, or if there's a way around it? And yes, I DO have "Enable per content node access control settings" checked for the content type.

# Answer
> 1 votes
you can use Content Access Module.

A quick view :

> "This module allows you to manage permissions for content types by role and author. It allows you to specifiy custom view, edit and delete permissions for each content type. Optionally you can enable per content access settings, so you can customize the access for each content node."

I hope it works for you

# Answer
> 0 votes
Another way is to implement hook\_node\_access in a custom module to set the permissions you need programmatically https://api.drupal.org/api/drupal/modules%21node%21node.api.php/function/hook\_node\_access/7

if you "need particular nodes to limit editing by role." I also propose to take a look at the workflow module. You can set some states for the node (e.g in review)and only some specific roles can edit the node in that state.

---
Tags: 7, users
---


# Question
Title: Is there any option to import my excel to Views?
I am new for drupal 7.

I got exported excel from view using Views Data Export Module.

My question is,

Is there is any option to import my excel sheet to view.

Kindly help me to achieve this...

# Answer
You can do by using PHP Excel module. This module is for handling the export or import of Excel files.
> 1 votes

# Answer
Yes you can use feeds module to import csv files into nodes. Then you create any view you want from the newly created nodes.
> 0 votes

---
Tags: views, importing-exporting
---


title: How do I render sub-menus?

text:
# Question
Title: How do I render sub-menus?
I have a Drupal 7 installation that, for the purposes of this question, has just the core modules.

Using the Structure-\>Menus-\>Main Menu form, I added some items to the menu and, using a Mytheme\_links\__system\_main\_menu($main\_menu) in the template file, dumped the menu items using print\_r, just to check what is being passed through.

So far so good.

Now, in the Structure-\>Menus-\>Main Menu form, I add some child items beneath one of the top level items by dragging these items to the right one space under the parent. Then I clicked "Show as expanded" on the parent item and saved the configuration.

When I dump the $main\_menu variable again, only the parent items are shown. The child items are never shown.

Can anyone help me understand how to ensure that the child items are rendered to the $main\_menu array?

I don't really want to add pre-themed menu modules as there is a very simple but very specific layout that I need to achieve. Can the default Drupal menu module handle sub-menu items?

# Answer
I think the problem your running into is that the menu system by default only returns the submenu on the path for that parent menu item.

When I've built bootstrap based themes (and wanted all the submenus expanded for dropdown menus) I've used `hook_links___system_main_menu($vars)`

It ends up looking like this (can't help but feel there must be an easier way!):

```
    /**
    * Implements hook_links__system_main_menu().
    *
    * @param array $vars
    * @return string
    *  Themed HTML for bootstrap 3 ready main menu.
    */
    function MYTHEME_links__system_main_menu($vars) {
    // Get the active trail
    $menu_active_trail = menu_get_active_trail();
    // Initialise our custom trail.
    $active_trail = array();

    // Get current path
    $dest = drupal_get_destination();
    if (is_string($dest['destination'])) {
      $paths = explode('/', $dest['destination']);
      // Loop through and add all active paths
      foreach ($paths as $path) {
        // Read previous element added to active trail (using array values
        // preserves original array).
        $safe = array_values($active_trail);
        $previous = array_pop($safe);
        if ($previous) {
          $active_trail[] = $previous . '/' . $path;
        }
        // Or this is the first one
        else {
          $active_trail[] = $path;
        }
      }
    }

    // UL classes
    $class = implode($vars['attributes']['class'], ' ');
    $html = '<ul class="' . $class . '"';
    // Check if there is an ID set (not if it's a dropdown sub-menu).
    if (isset($vars['attributes']['id'])) {
      $html .= ' id="' . $vars['attributes']['id'] . '"';
    }
    $html .= '>';
    // Iterate links to build menu.
    foreach ($vars['links'] as $key => $link) {

      // Check this is a link not a property.
      if (is_numeric($key)) {
        $sub_menu = '';
        $li_class = array();
        $a_class = array();

        // Check if link is in active trail and add class.
        if (in_array($link['#original_link']['link_path'], $active_trail)) {
          $li_class[] = 'active-trail';
        }
        if ($link['#original_link']['link_path'] == end($active_trail)) {
          $li_class[] = 'active';
        }
        // Check if last element in list and see if LI contains actual link
        $link['#attributes']['class'][] = strtolower(str_replace(array('& ', ' '), array('', '-'), $link['#title']));
        $link_title = $link['#title'];
        // Open subscribe in a new window.
        if ($link_title == 'Subscribe') {
          $link['#localized_options']['attributes']['target'] = '_blank';
        }
        if (isset($link['#localized_options']['attributes'])) {
          $link['#attributes'] = array_merge($link['#localized_options']['attributes'], $link['#attributes']);
        }

        // Check if we have a submenu.
        if (!empty($link['#below'])) {
          // Check if lvl 1, if higher do other stuff
          if ($link['#original_link']['depth'] < 2) {
            $li_class[] = 'dropdown';
            $link_title .= '<b class="caret"></b>';
            $link['#attributes']['class'][] = 'dropdown-toggle';
            $link['#attributes']['data-toggle'] = 'dropdown';
          } else {
            $li_class[] = 'dropdown-submenu';
            $link_title .= '<b class="caret"></b>';
          }
          // Theme submenu
          $sub_menu = theme('links__system_main_menu', array('links' => $link['#below'], 'attributes' => array('class' => array('dropdown-menu'))));
        }
        // Build classes string
        $classes = '';
        if (!empty($li_class)) {
          $classes = ' class="' . implode($li_class, ' ') . '"';
        }
        $html .= '<li' . $classes . '>' . l($link_title, $link['#href'], array('html' => 'true', 'attributes' => $link['#attributes'])) . $sub_menu . '</li>';
      }
    }
    $html .= '</ul>';
    return $html;
    }

```

And finally add a new `$main_menu_expanded` for the page template in `hook_preprocess_page`

```
  // Get the entire main menu tree
  $main_menu_tree = menu_tree_all_data('main-menu');

  // Add the rendered output to the $main_menu_expanded variable
  $vars['main_menu_expanded'] = menu_tree_output($main_menu_tree);

```

A bit overkill for what you want as it adds all the bootstrap specific markup, but it's a solution.
> 1 votes

# Answer
It may be caused by the "Show as expanded" unchecked checkbox by default on your menu items edition page. Check 'admin/structure/menu/item/{mid}/edit'

---

By the way, devel's module dpm(object) function is the Drupal way of print\_r / var\_dump inspecting things.
> 1 votes

# Answer
The `$main_menu`variable only contains first level menu items.

> The default $main\_menu variable in page.tpl.php is set to menu\_main\_menu(), which is a contextual view of the main menu tree.
>
> To get your desired output, you need to get the entire menu tree using menu\_tree\_all\_data() and menu\_tree\_output().

Have a look at this question. Show all nested menu links in Drupal 7
> 0 votes

---
Tags: 7, theming, routes
---


# Question
Title: Can www.example.com/node/123 be used as a canonical url?
We are sharing some of our content with partners and want to include a canonical reference to the pages on our Drupal site.

I like the idea of using `www.example.com/node/$nid` for the simplicity of it, but I don't know whether it is acceptable for a canonical url to be redirected (as is commonly done with clean urls, path\_auto, redirect, etc)?

# Answer
Permanently redirecting the `canonical` URL is allowed, but discouraged by RFC 6596:

> To better ensure that applications properly handle the canonical link relation, administrators ought to consider the following guidelines:
>
> \[…\]
>
> Avoid designating the target (canonical) as:
>
> \[…\]
>
> The source IRI of a permanent redirect (for HTTP, this refers to 300 and 301 response codes defined in Sections 10.3.1 and 10.3.2 of \[RFC2616\]
> 2 votes

---
Tags: 7, uri
---


# Question
Title: How can I find a module or activity that is excessively writing to the database?
**Problem:**

We have two productions servers: primary and failover. The two machines are linked via mysql replication. The mysql relay logs are clogging and bringing servers down the failover server. I see dozens of mysqld-relay-bin.000Xxxx files in /var/lib/mysql on the failover box.

**My Question:**

*How might I find if a module or some other activity is doing excessive database writes?*

**Why am I asking a sql question on *DA*?**

Now I'm asking this in Drupal Answers because we're trying to trace this from source to destination. I have a suspicion that we have a module that is a bit over-aggressive at logging. We only have two content editors and changes are made on a few pages a day. I've also asked a similar question on https://superuser.com/questions/869776/ to see if there is a more mysql-specific remedy.

**Master my.cnf**

```
$ cat /etc/my.cnf
[mysqld]
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
user=mysql
# Disabling symbolic-links is recommended to prevent assorted security risks
symbolic-links=0

# sync
log-bin=mysql-bin
server-id=1
expire_logs_days = 1
max_binlog_size  = 100M
.
.
.
# sync config
log-bin = /var/log/mysql/mysql-bin.log
binlog_do_db=drupal
server-id=1

```

**Replicant (Slave) my.cnf**

```
$ cat /etc/my.cnf
[mysqld]
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
user=mysql
# Disabling symbolic-links is recommended to prevent assorted security risks
symbolic-links=0

server-id=2
master-host=xxx.xx.xx.xxx
master-user=slave_user
master-password=XXXXXXXXXXXXXXX
master-connect-retry=60
replicate-do-db=drupal
slave-skip-errors = 1062,1054
expire_logs_days = 2
max_binlog_size  = 100M
ssl

```

**Various or interesting finds in the logfile via `tail -n 10000 messages | grep drupal | grep -v "page not found" | grep -v "access denied"`**

```
Warning: in_array() expects parameter 2 to be array, string given in context_menu_tree_add_active_path() (line 128 of /var/www/html/sites/all/modules/context_menu_block/context_menu_block.module).

```

**Other considerations:**

* Drush runs once an hour via the OS's crontab. We pull in multiple calendar and RSS feeds to keep updated content.
* We've recently migrated this site to Drupal. Our log files still indicate a few broken, dead links that spiders are finding. Which if I had db\_log/watchdog enabled would be an obvious culprit.

# Answer
I recommend turning on mysql query log and examining types of queries flooding your server.

Or, pay for a product like New Relic or AppDynamics which provide per-url PHP performance metrics (including DB usage) of your application on web servers.
> 3 votes

# Answer
I'd agree with @tenken. There are two types of query log - normal and slow - and you can modify the config on the fly from e.g. mysql cli. Drupal logging entries normally include the module name doing the logging.

If it is not watchdog() type calls it might be more difficult. You could look into the capabilities of the 'devel' module, which includes some drupal-level Db logging.

I would add that perhaps some tuning of the replication is in order. Personally, I'd start with a lower binlog max size, so the systems are closer together. I know that sounds counterintuitive, but...
> 1 votes

# Answer
You should take a look at your error logs too.

The DB slow down may not be a performance issue with a module but may be driven by a module that is tossing errors or even just warnings.

Every time Drupal watchdog logs a PHP notice, warning or error, PHP executes slower and the writing operation locks the database. That could be why your replications isn't happening.

Definitely try New Relic. There are so many layers of processing that get used building out a page that it's very hard to track down where a performance issue may be. Even the free version of New Relic help pinpoint issues.

Lastly, and I could be off base here, It seems you have a lot of modules massaging your code before display. Depending on your caching that could be eating you machine resources. I'm a big fan a Damien, but modules like cpn can make efficient caching difficult. Maybe your best course of action is to get a machine for just your db and have two head head that connect to a DB server with a slaved replication backup. If you separate out your web heads from your DB then you might find you can tune your boxes for much better performance.

I've done a lot of speculation here so forgive me if I'm just off base.
> 1 votes

# Answer
You can try to find a very core hook or function (e.g. https://api.drupal.org/api/drupal/includes%21common.inc/function/drupal\_write\_record/7 ) that writes in the database and then use watchdog and backtrace (e.g. watchdog('mydebug',print\_r(debug\_backtrace(), 1)) to get a comprehensive list about who called it

see also https://www.lullabot.com/blog/article/quick-and-dirty-debugging

Of course anything else can be used for logging instead of watchdog
> 1 votes

---
Tags: database
---


title: Drupal 6 Pager not working

text:
# Question
Title: Drupal 6 Pager not working
I am using pager\_query and theme\_pager function as below.But unfortunately the pager is not getting displayed.Please help.

```
function advanced_product_search() {
    $output = "";

    $sectors = $material_types = $resource_types = array();
    $where_array = array();
    $node_data = array();
    $product_query = "SELECT n.* FROM {node} n INNER JOIN {term_node} tn ON n.nid = tn.nid ";
    $product_count_query = "SELECT COUNT(DISTINCT(n.nid)) FROM {node} n
        INNER JOIN {term_node} tn ON n.nid = tn.nid ";

    $product_query .= " WHERE n.type = 'product' ";
     if(isset($_POST['keyword']) && !empty($_POST['keyword'])){
        $key_word = check_plain($_POST['keyword']);
        $product_query.= " AND n.title LIKE '%$key_word%' ";
        $product_count_query.=" AND n.title LIKE '%$key_word%' ";
    }

    if(!empty($_POST['sector'])){
      $sectors = $_POST['sector'];
    }

    if(!empty($_POST['material_type'])){
      $material_types = $_POST['material_type'];
    }

    if(!empty($_POST['resource_type'])){
      $resource_types = $_POST['resource_type'];
    }

    $terms = array_merge($sectors ,$material_types ,$resource_types);
    if(!empty($terms)){
      $count = 1;
      $terms_list = "";
      foreach($terms as $tid){
        if($count < count($terms)){
          $terms_list.="$tid,";
        }else{
          $terms_list.="$tid";
        }
        $count++;
      }
      $product_query.=" AND tn.tid IN ($terms_list)";
      $product_count_query.=" AND tn.tid IN ($terms_list)";
    }

    $product_query.=" GROUP BY n.nid ORDER BY n.changed DESC ";
    $product_count_query.=" GROUP BY n.nid ORDER BY n.changed DESC ";

    $product_array = array();
    $product_query_result = pager_query($product_query, 5, 0, $product_count_query);
    while ($node = db_fetch_object($product_query_result)) {
      $node_data = node_load($node->nid);

      if($_POST['accredited'] == 'on'){
        if(empty($node_data->field_right_way_accredited[0]['value']) || !$node_data->field_right_way_accredited[0]['value']){
          continue;
        }
      }

      $product_array[] = array(
        'nid'=>$node_data->nid,
        'title'=>$node_data->title,
        'price'=>$node_data->sell_price,
        'image'=>$node_data->field_image_cache[0]['filepath'],
        'url'=> $node_data->path
      );
    }

    $output .= theme('ssa_product_search_template', $product_array);
    $output .= theme('pager', NULL, 5, 0);
    return $output;
}

```

# Answer
Solved this problem by correcting the fourth argument of pager\_query function i.e **$product\_count\_query**.

Pager query takes the fourth argument as an SQL query to count the number of matching records.It should a valid sql query.
> 0 votes

---
Tags: 6, paging
---


# Question
Title: How to tell Drupal to look for templates in module directory?
I'd like to provide template implementation in my module and allow themes to override it. Basically, I add a suggestion by this simplified code:

```
function attach_preprocess_node(&$vars) {
  $vars['theme_hook_suggestions'][] = 'node__test';
}

```

(I don't want to use hook\_theme to add a new theme because I want to reuse preprocess node functions. The theme name are awkward but I don't want to write node\_*attach*\_% to avoid confusion with node type.)

Then I use hook\_theme\_registry\_alter() to add module path:

```
function attach_theme_registry_alter(&$theme_registry) {
  $path = drupal_get_path('module', 'attach') . '/themes';
  $theme_registry_copy = $theme_registry;
  _theme_process_registry($theme_registry_copy, 'phptemplate', 'theme_engine', 'node', drupal_get_path('module', 'node'));
  $theme_registry += array_diff_key($theme_registry_copy, $theme_registry);
  if (!isset($theme_registry['node']['theme paths'])) {
    $theme_registry['node']['theme paths'] = array();
  }
  if (!isset($theme_registry['node']['theme paths'])) {
    $first_element = array_shift($theme_registry['node']['theme paths']);
    if ($first_element) {
      array_unshift($theme_registry['node']['theme paths'], $first_element, $path);
    }
    else {
      array_unshift($theme_registry['node']['theme paths'], $path);
    }
  }
}

```

However it does not work. That means: the file themes/node--super.tpl.php is not used. It is used only if I copied it to the theme folder.

# Answer
> 4 votes
Basically you can save yourself a bit of headache by implementing `hook_theme()` instead of altering the registry.

I suggest a look at theming\_example in the Examples project, handily reproduced on this API doc page, perhaps with especially helpful code on this page.

```
function theming_example_list_page() {
  $items = array(
    t('First item'),
    t('Second item'),
    t('Third item'),
    t('Fourth item'),
  );

  // First we'll create a render array that simply uses theme_item_list.
  $title = t("A list returned to be rendered using theme('item_list')");
  $build['render_version'] = array(
    // We use #theme here instead of #theme_wrappers because theme_item_list()
    // is the classic type of theme function that does not just assume a
    // render array, but instead has its own properties (#type, #title, #items).
    '#theme' => 'item_list',
    // '#type' => 'ul',  // The default type is 'ul'
    // We can easily make sure that a css or js file is present using #attached.
    '#attached' => array('css' => array(drupal_get_path('module', 'theming_example') . '/theming_example.css')),
    '#title' => $title,
    '#items' => $items,
    '#attributes' => array('class' => array('render-version-list')),
  );

  // Now we'll create a render array which uses our own list formatter,
  // theme('theming_example_list').
  $title = t("The same list rendered by theme('theming_example_list')");
  $build['our_theme_function'] = array(
    '#theme' => 'theming_example_list',
    '#attached' => array('css' => array(drupal_get_path('module', 'theming_example') . '/theming_example.css')),
    '#title' => $title,
    '#items' => $items,
  );
  return $build;
}

```

This is all for Drupal 7.

# Answer
> 6 votes
Maybe this one works:

```
/**
 * Implements hook_theme().
 */
function MODULE_theme($existing, $type, $theme, $path) {
  return array (
    'node__CONTENTTYPE' => array (
      'variables' => array( . . . ),
      'template' => 'node--CONTENTTYPE' ,
      'base hook' => 'node',
      'path' => drupal_get_path('module', 'MODULE'),
    ),
  );
}

```

Important here is the key '**base hook**'.

# Answer
> 2 votes
I like dashohoxha's solution of the hook\_theme implementation but was not able to get it working. After some more googling I found a variation that worked nice for me:

```
/**
 * Implements hook_theme().
 */
function mymodule_theme($existing, $type, $theme, $path) {
  $theme = array();
  $theme['node__blog_post'] = array(
    'render element' => 'content',
    'base hook' => 'node',
    'template' => 'node--blog_post',
    'path' => drupal_get_path('module', 'mymodule') . '/templates',
   );
  return $theme;
}

```

Notes: my custom module is called 'mymodule' and my custom content type is called 'blog\_post'. The tpl.php that I use is called 'node--blog\_post.tpl.php' and it is located in the 'templates' sub folder of my module.

# Answer
> 2 votes
Here is my snippet to declare views templates stored in the "template" folder of my "custom\_module":

```
/**
 * Implements hook_theme_registry_alter().
 */
function custom_module_theme_registry_alter(&$theme_registry) {
  $extension   = '.tpl.php';
  $module_path = drupal_get_path('module', 'custom_module');
  $files       = file_scan_directory($module_path . '/templates', '/' . preg_quote($extension) . '$/');

  foreach ($files as $file) {
    $template = drupal_basename($file->filename, $extension);
    $theme    = str_replace('-', '_', $template);
    list($base_theme, $specific) = explode('__', $theme, 2);

    // Don't override base theme.
    if (!empty($specific) && isset($theme_registry[$base_theme])) {
      $theme_info = array(
        'template'   => $template,
        'path'       => drupal_dirname($file->uri),
        'variables'  => $theme_registry[$base_theme]['variables'],
        'base hook'  => $base_theme,
        // Other available value: theme_engine.
        'type'       => 'module',
        'theme path' => $module_path,
      );

      $theme_registry[$theme] = $theme_info;
    }
  }
}

```

Hope it helps someone.

# Answer
> -1 votes
I asked this once on Stack Overflow. Basically, you have to implement `hook_theme_registry_alter()` to get your path added to the theme hook template path; then, on `hook_enable()`, you call drupal\_theme\_rebuild() to clear the theme registry cache and get your path scanned for templates.

---
Tags: 7, theming
---


# Question
Title: How do I override a default view template from another module?
Drupal provides `hook_theme()`. But is there a hook\_theme\_alter()? I'm looking for something like `hook_menu_link_alter()`, which overrides hook menu entries, but for the theme. I want to modify a view hook theme entry so I can specify where to look for one of my custom templates. I am not interested in specifying it through the Views interface, since it look for the theme template inside the theme folder, and I want my template in a feature module.

I found `hook_theme_registry_alter()` and `_theme_process_registry()`. You can answer which one is the best to use and why.

Which of these keys should I modify in order to make the view pickup the template from the module?

If I put views-data-export-xml-header--richard-feeds-nokia-movies--views-data-export-1 in the feature, the View defaults to pick up views-data-export-xml-header.tpl.php. If I put that template in the theme layer, the view picks it up (even with the registry alter hook in place).

# Answer
Your feature should implement `hook_theme_registry_alter()`. The use case you describe is exactly what that hook is for. The example code linked on the API page should get you started. The basic idea is to target the entry that corresponds to the entry that `views_theme()` is inserting into the registry, and change the template to match the one in your feature.
> 13 votes

# Answer
This is the code I use to declare a view template stored in the *template* folder of a custom module.

```
/**
 * Implements hook_theme_registry_alter().
 */
function custom_module_theme_registry_alter(&$theme_registry) {
  $extension   = '.tpl.php';
  $module_path = drupal_get_path('module', 'custom_module');
  $files       = file_scan_directory($module_path . '/templates', '/' . preg_quote($extension) . '$/');

  foreach ($files as $file) {
    $template = drupal_basename($file->filename, $extension);
    $theme    = str_replace('-', '_', $template);
    list($base_theme, $specific) = explode('__', $theme, 2);

    // Don't override base theme.
    if (!empty($specific) && isset($theme_registry[$base_theme])) {
      $theme_info = array(
        'template'   => $template,
        'path'       => drupal_dirname($file->uri),
        'variables'  => $theme_registry[$base_theme]['variables'],
        'base hook'  => $base_theme,
        // Other available value: theme_engine.
        'type'       => 'module',
        'theme path' => $module_path,
      );

      $theme_registry[$theme] = $theme_info;
    }
  }
}

```

You should be easily able to fork it override an existing theme instead of adding a new one. Hope it helps someone.
> 1 votes

---
Tags: views, theming, hooks
---


title: Drupal pagination help

text:
# Question
Title: Drupal pagination help
I am not sure how this works, hence need a little help. I am fetching some nodes using `db_select` and rendering this in a `foreach` loop in a custom template file. I would give a hint of my code :

```
$nodes = db_select('node', 'n')
// Some fields...
// Some conditions...
// ->execute();
$nodes = $nodes->fetchAll();
return theme('my_custom_callback', array('nodes' => $nodes));

```

Now I get this $nodes in my tpl file and print them to the design. But what I want is to have the Drupal default pagination effect (probably using the `PagerDefault` facility). I have come accross many examples of the use of `PagerDefault` but I am not sure how to render the pagination in my tpl file.

Please note using a Drupal view or a table theme is not an option in my case.

Help appreciated...

# Answer
Well as no one responded, I searched a bit and found a normal PHP function to achieve the same. I know it may not be a Drupal way, but its for them who are looking for a quick solution for now (like me). But would like to add that other answers to achieve this the specially the Drupal way is very much welcome. Also please note, I almost copy pasted the actual function, so you probably may want to modify that as per your UI (for actual function I have given the reference below) :

```
// This is the menu callback where $data are the records fetched to be displayed in this page, and $total_count is the total number of count of all the records.

$pager = pagination($current_page, $total_count, $record_limit, 2, "url-menu-page?page=%d");

$return_val = theme('my_callback_function', array('data' => $data, 'pager' => $pager));

return $return_val;

```

And here goes the actual pagination building function :

```
/**
 * Displays pagination links based on given parameters
 *
 * @param int $currentPage - current page
 * @param int $itemCount - number of items to paginate, used to calculate total number of pages
 * @param int $itemsPerPage - number of items per page, used to calculate total number of pages
 * @param int $adjacentCount - half the number of page links displayed adjacent to the current page
 * @param (string|callable) $pageLinkTemplate - pagination URL string containing %d placeholder or a callable function that accepts page number and returns page URL
 * @param boolean $showPrevNext - whether to show previous and next page links
 * @return void
 */
function pagination($currentPage, $itemCount, $itemsPerPage, $adjacentCount, $pageLinkTemplate, $showPrevNext = true) {
  $pager = '';
  $firstPage = 1;
  $lastPage  = ceil($itemCount / $itemsPerPage);
  if ($lastPage == 1) {
      return;
  }
  if ($currentPage <= $adjacentCount + $adjacentCount) {
      $firstAdjacentPage = $firstPage;
      $lastAdjacentPage  = min($firstPage + $adjacentCount + $adjacentCount, $lastPage);
  } elseif ($currentPage > $lastPage - $adjacentCount - $adjacentCount) {
      $lastAdjacentPage  = $lastPage;
      $firstAdjacentPage = $lastPage - $adjacentCount - $adjacentCount;
  } else {
      $firstAdjacentPage = $currentPage - $adjacentCount;
      $lastAdjacentPage  = $currentPage + $adjacentCount;
  }
  $pager = '<div class="pagination-hld"><h2 class="element-invisible">Pages</h2><div class="item-list"><ul class="pager">';
  if ($currentPage != $firstPage) {
    $pager .=  '<li class="pager-first first"><a href="' . (is_callable($pageLinkTemplate) ? $pageLinkTemplate($firstPage) : sprintf($pageLinkTemplate, $firstPage)) . '">« first</a></li>';
  }

  if ($showPrevNext) {
      if ($currentPage == $firstPage) {
      //$pager .= '<li title="Go to first page" class="pager-first first">< previous</li>';
      } else {
      $pager .= '<li title="Go to previous page" class="pager-previous"><a title="Go to previous page" href="' . (is_callable($pageLinkTemplate) ? $pageLinkTemplate($currentPage - 1) : sprintf($pageLinkTemplate, $currentPage - 1)) . '">‹ previous</a></li>';
      }
  }
  if ($firstAdjacentPage > $firstPage) {
      if ($firstAdjacentPage > $firstPage + 1) {
      $pager .=  '<span>...</span>';
      }
  }
  for ($i = $firstAdjacentPage; $i <= $lastAdjacentPage; $i++) {
      if ($currentPage == $i) {
      $pager .=  '<li class="pager-current">' . $i . '</li>';
      } else {
      $pager .=  '<li class="pager-item"><a title="Go to page '.$i.'" href="' . (is_callable($pageLinkTemplate) ? $pageLinkTemplate($i) : sprintf($pageLinkTemplate, $i)) . '">' . $i . '</a></li>';
      //$pager .=  "<li class='pager-item'><a title=\"Go to page $i\" href=\"' . (is_callable($pageLinkTemplate) ? $pageLinkTemplate($i) : sprintf($pageLinkTemplate, $i)) . '\">$i</a></li>\r\n";
      }
  }
  if ($lastAdjacentPage < $lastPage) {
      if ($lastAdjacentPage < $lastPage - 1) {
      $pager .=  '<span>...</span>';
      }
  }
  if ($showPrevNext) {
      if ($currentPage == $lastPage) {
      //$pager .=  '<li class="pager-next"><span>next ></span></li>';
      } else {
      $pager .=  '<li class="pager-next"><a href="' . (is_callable($pageLinkTemplate) ? $pageLinkTemplate($currentPage + 1) : sprintf($pageLinkTemplate, $currentPage + 1)) . '">next ›</a></li>';
      }
  }
  if ($currentPage != $lastPage) {
    $pager .=  '<li class="pager-last last"><a href="' . (is_callable($pageLinkTemplate) ? $pageLinkTemplate($lastPage) : sprintf($pageLinkTemplate, $lastPage)) . '">last »</a></li>';
  }
  $pager .=  '</ul></div></div>';

  return $pager;
}

```

Hope this helps somebody...

Original code credit goes to the author of this blog : http://salman-w.blogspot.in/2014/04/stackoverflow-like-pagination.html
> 0 votes

---
Tags: paging
---


title: Upload File upload and generate url

text:
# Question
Title: Upload File upload and generate url
I have a site where there are several links to a single file.

Is there a module that allows me to upload a file into the CMS, generate a link and use it as for these links?

The Module would need to keep the same file name if re-uploaded.

Thanks in advance.

# Answer
> 2 votes
Try to use Attachment Links module. Read the README.txt file for better understating.

---
Tags: files
---


# Question
Title: How to sort name by alphabetically in drupal views?
I have created view in this drupal 7 views,there are Two pages are created in that view.

> page 1:Images page
>
> page 2:List view page

here i have tried in List view page by using sort criteria of Name field(ASC or DESC). but Names are sorted in List view page correctly.

* When i am click Name field for sorting in second page(List view) automatically that fields are sorted in first page(Images) page also.
* That sorting is not working in views.
* First page taking only default sorting order.

Here is screen shorts

Here sorting values are not stored database permanently.If i click refresh button views default sorting behavior is added to that pages.

Is it possible to sort the two view pages permanently?

# Answer
we have a module called Views Glossary once u install the module we have to enable in stucture-\>views-\>glossary view like archive for dats and months
> 1 votes

---
Tags: views
---


# Question
Title: How to I create a backup of my content ONLY?
I'm debating between using Feeds module and Backup and Migrate and I'm not sure which would be the best option here.

Here's the scenario - I've two versions of the same site - both drupal 7, both have the same content types and taxonomy structure. One is live, one is on a development server. Due to some unclear communication a bunch of content edits were added to the live site that need to be merged in to the development site where we've made major improvements with Views and several stylistic changes, so we can't just dump the database and then move it without wiping out all the new content on the live site.

So does anyone have a good idea on how to best move JUST the content tables from the database? I know it will be different from install to install, but if you could help me get an idea of what to look for I can use the backup and migrate module and just exclude every table except those which I need.

Thanks in advance.

# Answer
> 5 votes
Node export is the best option to take backup for contents. One click export, import for the particular content types.

> This module allows users to ***export nodes*** and then ***import*** it into another Drupal installation, or on the same site.
>
> Using this module you can ***save yourself a lot of time*** setting up new websites that have similar nodes to websites you've already made, migrating nodes to new Drupal versions, or between development/staging/production sites.
>
> You will need the same content types for the imports to work (unless using Feeds to import), and ideally relevant compatibility with fields, and modules.

# Answer
> 2 votes
You can also use feature module to import functionality from one site to another site.

> The features module enables the capture and management of features in Drupal. A feature is a collection of Drupal entities which taken together satisfy a certain use-case. Features provides a UI and API for taking different site building components from modules with exportables and bundling them together in a single feature module. A feature module is like any other Drupal module except that it declares its components (e.g. views, contexts, CCK fields, etc.) in its .info file so that it can be checked, updated, or reverted programmatically.

Yon can export your views from deveolpment version of your site using feature module. It will export views into module and you can install this module like the other module into live site and views will be activate into your live site.

There are some feature related module which extend the functionality of the feature module.

# Answer
> 1 votes
Backup and Migrate won't help you here.

Options:

1. You could certainly use Feeds.
2. You could use Deploy (probably with UUID).
3. You could move the content manually.

Honestly, if the amount of content is under fifty-or-so nodes, I would do it manually, and call it a lesson learned. You can be done in an hour or two, and that'll be quicker than learning how to set this up with either of the other two options. Of course, if you want to learn some new tools (and probably use them in the future), options 1 and 2 would be the way to go.

# Answer
> 1 votes
For your specific scenario, Jayendra's answer is best; you should accept that answer, and do as he said (move your updated views to the live server rather than try to move just the content from live to dev). This is standard for Drupal.

If you want to move just the content, try Drupal to Drupal Migration, or one of the other answers -- but using features will be easiest.

# Answer
> 0 votes
You can use https://drupal.org/project/views\_data\_export to export your terms and nodes to XML into 2 separate feeds.

Then Feeds and https://drupal.org/project/feeds\_xpathparser to import the content.

You can also export into CSV and import using Feeds' CSV parser. That will work for simple cases, but multi-valued fields can be problematic.

Deploy is great, but it's a lot more work to setup for a one-off job.

# Answer
> 0 votes
It really depends on how complex your data is and what you want saved. If its just a couple of fields then you could create a view that has all the data in it. Copy it into excel then import it using feeds into your new site. It sounds messy but I imported more then 4000 nodes into a site this way and it only took an hour to setup, export then import. There are more complex ways of exporting the data using different modules.

---
Tags: 7, feeds, backups
---


# Question
Title: Meta tags, title and description not showing up on home page
I have a regular page set as the home page on my site. The Meta Tags, Title and Description are all set on the node, but do not show up on the home page.

Any ideas why?

# Answer
Try printing

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

```

in your `page.tpl.php` or `page--front.tpl.php` if youre using Meta tags
> 4 votes

# Answer
If you are using the MetaTag module (https://www.drupal.org/project/metatag), then there are separate settings for the front page.

Go to `/admin/config/search/metatags`, and add the Global: Front Page settings.
> 2 votes

# Answer
One way to add metas to your home page is by downloading Meta tags quick and activating path-based metatags. Then, when logged as admin, click on the "Path-based metatags" tab.
> 1 votes

# Answer
Most meta tags modules put them in node pages only, eg, pages built around a single content type. So, they won't show up in views or other pages, like the front.
> 0 votes

---
Tags: 7, meta-tags
---


# Question
Title: print out multiple values of a taxonomy field
In a taxonomy I have some fields for the terms. To print out 1 of these fields in a node.tpl I found this code:

```
<?php $term=taxonomy_term_load($node->field_hotel_tx_atmosphere['und'][0]['tid']);
$result=field_view_field('taxonomy_term',$term,'field_tx_headline','text');
print render($result); ?>

```

But this way I get only the first value - there are multiple terms selected.

How can I get all selected terms printed out?

# Answer
> 1 votes
`0` in `$node->field_hotel_tx_atmosphere['und'][0]['tid']` means that you are taking only first term so you should loop through array to get all terms.

I recommend entity\_metadata\_wrapper (available with Entity API module):

```
$wrapper = entity_metadata_wrapper('node', $node);
foreach ($wrapper->field_hotel_tx_atmosphere->getIterator() as $delta => $term_wrapper) {
  // prepare and render field value:
  $result = field_view_field('taxonomy_term', $term_wrapper->value(), 'field_tx_headline', 'text');
  print render($result);
}

```

or build a View to display selected data in the right way.

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


# Question
Title: How to add multiple forums for a single site in Drupal
I am working on a client portal and client needs multiple forums for the site based on the user priviledges.

**e.g.**

> www.example.com/forum1
>
> www.example.com/forum2
>
> www.example.com/forum3

Is it possible to create multiple forums in Drupal? If yes, any reference or steps please.

# Answer
The Drupal forum module allows creation of multiple forums. The module allows you to create 'forum containers' (groups of forums) and forums.

If combined with '**Advanced Forum**' and '**Forum Access**' modules it should be able to provide you with the facility to create multiple forums and control access by role to specific forums or containers.

The forum containers are actually taxonomy terms so you can customize the URLs for each container by editing the taxonomy term, eg /forum1 /forum2 etc.

To make the URL structure consistent between containers and forum topics, you may also require 'PathAuto' module, and to look at the URL alias patterns.

For **default pattern for forum topics** \- I use is:

```
forum/[node:taxonomy-forums:parents:join:/]/[node:taxonomy-forums:name]/[node:nid]

```

You might find this works better for you if you wish to customize the taxonomy term URLs.

```
[node:taxonomy-forums:url:path]/[node:nid]

```

**Pattern for forums and forum containers:**

```
forum/[term:parents:join-path]/[term:name]

```

or perhaps for consistency with custom URLs

```
[term:parent:url:path]/[term:name]

```
> 0 votes

---
Tags: nodes
---


title: Change the layout order of webform

text:
# Question
Title: Change the layout order of webform
Normally, a webform places the body content first and then the form after. I want to reverse it. I want the form to appear first and the body content to appear afterward. Is this possible?

# Answer
In Drupal the content of a page view is created by a template file and `$variables`. The variables are typically a simple PHP `string` or Drupal7 `render arrays` when the content is more complex than just a string, and the system composes all the render arrays into page output.

A render array for instance can be a Webform, or a Node of a Page (content type). When you place Node ID 1 which contains a Webform reference the system is really composing these 2 items into your 1 page.

A single key per render array may be a `#weight` value this `integer` value denotes where this content appears from top to bottom among the many render arrays composed by the system within a given Region of the page.

Yes, it is possible to *flip* or change the ordering of the Body field and the Webform presentation to the visitor. Typically you would do this in the theme layer of drupal by implementing a Drupal hook to change the weight value in a render array.

If you don't want to code alot there are numerous modules that can let you change the display of items on the page with little or not coding. One example is Display Suite (otherwise known as DS). It allows you to override or customize `view_modes` of content on your site.

For example I have on a website the default Drupal content type of Page, and I've configured Webform to allow webforms to be placed on Page Nodes. Using DS I could change all webforms to appear before the Body of the Page Node in a simple administrative UI:

I leave it to you to do additional research to find the tool(s) you are comfortable with to complete your task. I've outlined at least 2 here (DS and core APIs).

**EDIT**

To be clear, if you're using Webform as a content type directly (and not attaching it other content types) DS may not show you "Body" and "webform" fields on the Webform content type -- but the webform Node is still just a render array and its fields still have `#weight` values. I find it more useful to attach webforms onto content, then to use Webforms by themselves.
> 4 votes

---
Tags: webforms, theming
---


# Question
Title: Price by multiple attributes in Commerce
I need to dynamically alter a price based on the value of two attributes in Commerce. I'm quite new to commerce so not exactly sure how to achieve this. Using rope as an example, the price needs to vary based on both the length of the rope and it's diameter. I know I could create a line item for each length if that was the only variant, however due to both length and diameter being variable this becomes more of a challenge.

Anyone have any ideas?

# Answer
It will probably have to be done with custom Rules. If the price is calculated predictably via different measurements/attributes, you can use the Rules Event of Calculating Sell Price of Product. Conditions could vary, but a custom Action or Action set is probably going to be needed to calculate the price, and then set the price to the calculated value.

Maybe check out this link for an example of dynamically changing product prices.

http://www.drupalwoo.com/content/blog/drupal-commerce-and-rules-changing-product-price-dynamically
> 1 votes

# Answer
I believe what you're describing is best done using a product variation. The answer posted about using Rules is a good idea. I'm very, very new to Commerce, but I have an alternate approach that might work for you.

You'll start by creating a Product type of "rope": /admin/commerce/products/types

In that product type, you'll add two new fields: length and diameter.

I would suggest to you that you create ranges of length and diameter, as this will be the easiest method to control pricing. So your diameter will be a pulldown list of values. The length will also be a pulldown list, but contain ranges: "less than 4 feet", "4 to 8 feet".

With both of these fields you want to check: Enable this field to function as an attribute field on Add to Cart forms.

NOW! "Add a product" of the type "Rope". This is where things get a bit complex, but essentially you're going to create a product variation. Each variation of the product has to be created and have a price assigned by you. This can be HELL if you have a lot of options, as the amount of variations grows rapidly. Maybe outside the scope of this question, but I have found a way to auto-generate product variations: Moving or creating many product variations.
> 0 votes

---
Tags: commerce
---


title: Impossible to get my pager

text:
# Question
Title: Impossible to get my pager
I need to show in the same page a form and a table which shows all results from a webservice response.

```
function collectivite_search_user_form($form, &$form_state) {
    $form['name'] = array(
      '#type' => 'textfield',
      '#title' => t('Name'),
      '#required'   => True,
    );
    $form['firstname'] = array(
      '#type' => 'textfield',
      '#title' => t('Firstname'),
      //'#required'   => True,
    );
    $form['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Submit'),
    );
    if (isset($form_state['table'])) {
        $form['table'] = $form_state['table'];
    }
    return $form;
}

function collectivite_search_user_form_submit($form, &$form_state) {
    module_load_include('inc', 'collectivite', 'collectivite.api');
    $results = collectivite_ws_get_users($form_state['values']['name'], $form_state['values']['firstname']);
    if(is_object($results->Dossier)){
            $rows[] = array(
                'id'       => $results->Dossier->id,
                'nom'       => $results->Dossier->nom,
                'prenom'    => $results->Dossier->prenom,
            );
    }else{
        foreach($results->Dossier as $dossier) {
            $rows[] = array(
                'id'       => $dossier->id,
                'nom'       => $dossier->nom,
                'prenom'    => $dossier->prenom,
            );
        }

    }

    $paging = pager_array_splice($rows, 5);
    $header = array(t('id'), t('name'), t('firstname'));

    $form_state['table'] = array(
      '#theme' => 'table',
      '#header' => $header,
      '#rows' => $paging,
      '#empty' => t('Aucun résultat.')
    );
    $form_state['rebuild'] = True;
}

function pager_array_splice($data, $limit = 9, $element = 0) {
  global $pager_page_array, $pager_total, $pager_total_items;
  $page = isset($_GET['page']) ? $_GET['page'] : '';

  // Convert comma-separated $page to an array, used by other functions.
  $pager_page_array = explode(',', $page);

  // We calculate the total of pages as ceil(items / limit).
  $pager_total_items[$element] = count($data);
  $pager_total[$element] = ceil($pager_total_items[$element] / $limit);
  $pager_page_array[$element] = max(0, min((int)$pager_page_array[$element], ((int)$pager_total[$element]) - 1));
  return array_slice($data, $pager_page_array[$element] * $limit, $limit, TRUE);
}

```

It works fine except I cannot see the pagination. Can you see where is the problem ?

Thanks

# Answer
```
 function pager_array_splice($data, $limit = 9, $element = 0) {
      global $pager_page_array, $pager_total, $pager_total_items;
      $page = isset($_GET['page']) ? $_GET['page'] : '';

      // Convert comma-separated $page to an array, used by other functions.
      $pager_page_array = explode(',', $page);

      // We calculate the total of pages as ceil(items / limit).
      $pager_total_items[$element] = count($data);
      $pager_total[$element] = ceil($pager_total_items[$element] / $limit);
      $pager_page_array[$element] = max(0, min((int)$pager_page_array[$element], ((int)$pager_total[$element]) - 1));
      return array_slice($data, $pager_page_array[$element] * $limit, $limit, TRUE);
    }

    $output = pager_array_splice($yourarray, 5);

```

$output = ''; $your\_array = some\_method\_to\_get\_array(); $tree = pager\_array\_splice($your\_array, 5); // Do something with the 5 terms $output .= theme('pager', array('quantity' =\> 5));
> 0 votes

# Answer
It looks like you are missing a call to `theme('pager')` for your output. Also, to maybe simplify things, you could use `pager_default_initialize`. Below is an example from the Drupal.org API page.

```
// Now that we have the total number of results, initialize the pager.
pager_default_initialize($result->total, $num_per_page);

// Display the search results.
$output = theme('search_results', array('results' => $result->data, 'type' => 'remote'));

// Finally, display the pager controls, and return.
$output .= theme('pager');

```
> 0 votes

---
Tags: forms, paging
---


# Question
Title: How to store css & js in separate file & call in custom 'tpl' files through variable in drupal 7?
I have created a custom module where I have define my page url's & contents are created through my custom **tpl** files.

I am applying some css & js on those custom contents/pages/tpl files.

**What I want** : I don't want to add path of those css & js in all pages. I want to define those css & js in separate file & I want to call that css & js in my custom pages through variable. Simply I want to create a header file which hold my css & js. And I want to call that header file in my custom pages.

**Why I want to do this :** Right now the path of the css & js is not fixed. So if am I add `drupal_add_css()` & `drupal_add_js()` in every tpl file then will change the path in every tpl file. So I want to create a *header* file where am I put the css & js path & if the path will change then I have to change the path in only header file.

How can I implement this?

# Answer
If you do not want, or are unable, to modify the theme html or page templates, you can also use drupal\_add\_css and drupal\_add\_js in the page\_callback function defined in your modules menu array `youmodule_menu()`.

If you have access to the template.php of the theme, you can use the preprocess hook to assign a variable to the file name, then do an include in the html template. Or from within your module use drupal\_add\_html\_head, but this has limitations.

Using drupal\_add\_(css|js) the links go into the head element of those pages by default before the themeing phase begins, but you can also specify the boostrap phase and location.

**EDIT**

Using drupal\_get\_path from within `yourmodule_init` hook or the page\_callback, and with the css and js stored within your module structure, you can then add the css and js using the drupal\_add functions. This makes a single place you need to maintain the 'paths' to the files.
> 1 votes

# Answer
Use drupal\_add\_css and drupal\_add\_js function on that desired tpl to add css and js.

You can use CSS Injector and JS injector module. These module also support placement option to define on page or callback.
> 0 votes

# Answer
Rupesh is right, actually drupal\_add\_css and drupal\_add\_js are adding your files to the header of the website.

You don't have to call these in every tpl file, that is what preprocess functions are made for.

You could, for instance, implement a hook function "yourtheme\_preprocess\_page(&$variables)" (or \_preprocess\_node, or any other suitable preprocess) in your theme's template.php, then add your js with druapl\_add\_js.

If you have trouble with theme's preprocess function, my advice is to try the Zen theme which has these functions as commented placeholders.

If needed, you should be able to filter templates names with the preprocess &$variables parameter.
> 0 votes

---
Tags: 7, theming
---


# Question
Title: Drupal 7 theme('pager') -> PDOException: SQLSTATE[42S02]: Base table or view not found
first time i have asked for help on a forum for a very long time. Normally find what i need by viewing other posts... Well i'm really confused so need help.

I am trying to use `theme('pager')` in Drupal 7 to have pagination for my table results i get from a `db_select` query.

The below query produces an error when i include the line:

`$output .= theme('pager');`

If i leave this line out i get the expected limited 5 results from my table.

My code:

```
// Set external databse
db_set_active('nondrupal');

// build query to get desired results
$query = db_select('diary', 'n')
->fields('n', array('photo_id', 'photo'))
->orderBy('photo_id', 'DESC');

//Create a new object from extend. The reason for this is that extend() creates a
new object which wraps the current object (Decorator pattern).
$query = $query->extend('PagerDefault')->limit(5);

// Execute query and add to array
$result = $query->execute();

// empty output var
$output = NULL;

// Loop through results and output each row for chosen columns
foreach($result as $row) {
$output .= $row->photo_id.': '.$row->photo.'<br />';
}

// Show pagination in output
$output .= theme('pager');

// echo output to screen
echo $output;

// Set db connection back to default (drupal)
db_set_active();

```

The page renders fine without the `theme('pager')` line.

With it i get an error:

```
Additional uncaught exception thrown while handling exception.
Original

PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table
'dbMYDATABASENAME.semaphore' doesn't exist: SELECT expire,
value FROM {semaphore} WHERE name = :name; Array ( [:name] =>
theme_registry:runtime:garland:cache ) in lock_may_be_available() (line 167
of /homepages/28/d228752694/htdocs/drupal7/includes/lock.inc).

```

Base table or view not found seems to be the key but i cannot see why including the theme function causes this error. I have a basic Drupal 7 install.

Your help is appreciated!

Madmilner

# Answer
The error is down to the:

```
// Show pagination in output
$output .= theme('pager');
// echo output to screen
echo $output;

```

being above `db_set_active();`

Not sure why this is but it fixes the problem.

Thanks
> 0 votes

---
Tags: paging, database
---