# Question
Title: hook_field_presave() isn't getting called
**Summary**

I need to edit some data before it gets saved, and `hook_field_presave()` looks like exactly what I need, but it doesn't get called for some reason.

**The Scenario**

I'd like to edit data coming from changes to the location field (location module), so that I can look up latitude and longitude information when none is provided and make sure it gets saved.

**The implementation**

At the moment I'm just adding the hook to the location.module for testing purposes before moving them into a separate module. The code I'm using is this:

```
function location_field_presave($entity_type, $entity, $field, $instance, $langcode, &$items) {
  watchdog('location', 'testing location_field_presave', array(), WATCHDOG_NOTICE);
}

```

However, the dblog is never updated with my message; the code never runs.

# Answer
> 3 votes
If you are editing an enabled module, you need to first disable, and then re-enable it. Drupal saves in cache the list of hooks implemented by modules; the one I described is the way to force Drupal to update that cache.

hook\_field\_presave() is invoked for the module implementing the field; the other modules should implement hook\_field\_attach\_presave(). If the Location module is not implementing the field, it should implement `hook_field_attach_presave()`, which is what your module should do too.

The documentation is not much clear about this; but looking at field\_attach\_presave() is a little more clear what happens.

```
function field_attach_presave($entity_type, $entity) {
  _field_invoke('presave', $entity_type, $entity);

  // Let other modules act on presaving the entity.
  module_invoke_all('field_attach_presave', $entity_type, $entity);
}

```

\_field\_invoke() invokes the hook for the module implementing the field; module\_invoke\_all() invokes the hook implemented by any module.

That is why the documentation for `hook_field_presave()` says, "Define custom presave behavior for this module's field types."

---
Tags: hooks, entities
---


title: Convert your views into a custom module

text:
# Question
Title: Convert your views into a custom module
I'm using Views 3 on Drupal 6.

A while back I read an article how you can take your views and put it in your "custom' module folder (granted you've set this up for custom theme functions). I haven't had much need for it lately, but recently I've been doing a lot of work for a client that has needed a bunch of reworking of their Views and CSS related to them. This has turned into a bit of a nightmare trying to make sure that they then take my exported views from my development server to their server and import them correctly (sometimes they rename them, sometimes settings are not exported for whatever reason, etc).

A while back a read an article about converting your views into modules and it seemed pretty straight forward, but now I can't find it. Could anyone point me in the right direction? All I could find is a 50 minute long video tutorial, and I would rather just have an article I can skim.

Thanks!

EDIT:

The below link seems like it should work, but I'm not sure what I'm doing wrong. It just dumps all the views export code at the top of the page. What I did:

Put this into my "sitetheme.module"

```
function sitetheme_views_api() {
   return array(
      'api' => 3,
  );
}

```

Created this separate file named "sitetheme.views\_default.inc". Which I put in this code:

```
/**
* Implementation of hook_views_default_views().
 **/
function sitetheme_views_default_views(){
  $files = file_scan_directory(drupal_get_path('module', 'sitetheme'). '/views',     '.view');
  foreach ($files as $filepath => $file) {
  require $filepath;
  if (isset($view)) {
 $views[$view->name] = $view;
  }
 }
  return $views;
}

```

Then I made a new folder in my sitetheme module called "views", took the export code and saved it something like "myexportview.view" and saved it under the "views" folder.

Then when I upload these files to the client server it just dumps all the code at the top of the admin/build/views page.

Any idea what I did wrong? I seem to be following the directions exactly but I'm not sure what I'm missing...

---

It appears that I had to put a `<?php` at the top of the `myview.view` export file. However, now Drush doesn't work... I get a fatal error from Drush when I try to clear the cache:

> Fatal error: \__clone method called on non-object in /Users/mycomputer/Sites/mysite/htdocs/includes/common.inc on line 1733

# Answer
> 4 votes
When the Bulk Export module (part of the Chaos Tools Suite module) is enabled, it exposes a page (admin/structure/bulk-export) where views can be exported.

What you need to do is selecting the views you want to export, enter the short name of the module that will contain the views, and click on the "Export" button.

The page that will appear next contains three text area fields (`<module name>` is the short name you entered in the previous page):

* One is for the content to place in `<module name>.info`
* The second is the content to place in `<module name>.module`
* The last is the content to place in `<module name>.views_default.inc`

The differences I can see between the code the module tells me to use, and the one you are showing are:

* The implementation of `hook_views_api()` is the following.

```
/**
 * Implements hook_views_api().
 */
function sitetheme_views_api($module, $api) {
  if ($module == 'views' && $api == 'views_default') {
    return array('version' => 2);
  }
}

```
* The implementation of `hook_views_default_views()` is the following.

```
/**
 * Implements hook_views_default_views().
 */
function sitetheme_views_default_views() {
  $views = array();

  $view = new view();

  // …

  return $views;
}

```

`$views` is an array of objects of the `view` class.

---
Tags: views, theming, 6
---


title: Styling Menu Mini panels

text:
# Question
Title: Styling Menu Mini panels
I'm having an issue with styling my menu mini panel hover.

Here's the site with the megamenu I'm working on: http://drupal.scienceworld.ca

As I'm rather new to JS, I was wondering what the best way to center the foldout menu in the browser would be?

# Answer
This isn't exactly a Drupal question but if you add the following to your CSS this will accomplish I think what you want.

```
div.qtip {
  top: 170px !important;
  left: 370px !important;
}

```

Adjust the values to suite your needs.

Edit: You may want to qualify that block of CSS further by prepending with it's wrapper or something, just to give it context and not break these qtip menus in other places
> -1 votes

---
Tags: routes, javascript
---


# Question
Title: Webform in block allowing clicking on send button and redirecting to page view, without validation the fields even when they are empty
Webform in block is allowing to click on send button and redirecting to page view, without validation the fields even when they are empty.

so if I come to the website and click on submit (on my form in block) instead of validationd and showing the little popup it redirects me to the form page view url.

But when I start typing something in my email fieled, then after clicking on submit I get a popup that email is in wrong format etc.

How to correct the behavior so that the popup shows the message like "the field is empty" etc.

Is it a bug of webform or am I missing something?

# Answer
> 0 votes
This is because you somehow missed making the E-mail field *mandatory*.
You can do so by following the steps given below:

1. Edit the existing webform content at : yourhost.com/admin/content and selecting *edit* for your webform.
2. Click the "Webform" tab, and check the "MANDATORY" option for the required field.
3. Click "Save". Thats it!

---
Tags: webforms
---


# Question
Title: Content type structure (nested content: Gallery / Photo)
I've been digging for some days how to organize my Drupal 7 site. I want to build a site with multiple galleries, each one of them with multiple photos: \- The galleries will show a cover photo, a description and thumbnails of the pictures; \- Each photo will have a title, a description, date, will allow for comments, have tags, etc. I want both the gallery and the photos as nodes (so I can have a page for a gallery and a page for each single photo with different layout). So, I thought this would be the structure of the content types, where 1 gallery has multiple photos:

## **content type: GALLERY**

* description (text)
* cover (image)
* **photo\_entries (unlimited | content type: PHOTO)**
* ...

## **content type: PHOTO**

* file (image)
* title (text)
* date\_taken (text)
* ...

I tried a solution (like the one explained here:http://megadrupal.com/blog/creating-an-image-gallery-in-drupal-7) where I have an unlimited image field in my gallery, but I really want the photos to be nodes and this is the thing I don't know how to do. I've been unsuccessfully trying using some modules like Views and entity reference, or even taxonomy, but I'm not sure what should be the approach to get this. This can be a very simple question and I'm sorry if it is, but I'm stuck... I really appreciate if someone could give me advice and put me on the way.

# Answer
> 0 votes
I think I found a solution for this using the Node Gallery module. Here is a quote about it (from the module's project page):

> ... allows you to create multimedia galleries where both the galleries and the gallery items are nodes (as opposed to gallery items being file fields, like Media Gallery).

---
Tags: 7, nodes, media
---


title: How do I add divs to a sitemap?

text:
# Question
Title: How do I add divs to a sitemap?
I have the Sitemap module installed and it creates an unordered list of my chosen menu's items.

Main Menu looks like this:

Home \- submenuitem1 \- submenuitem2 \- submenuitemn

Services \- submenuitem1 \- submenuitem2 \- submenuitemn

References \- submenuitem1 \- submenuitem2 \- submenuitemn

Links \- submenuitem1 \- submenuitem2 \- submenuitemn

How can I add DIVs to each main menu item with its subitems ( Home+subemenuitems, Service+submenuitems etc.) ?

I managed to override site\_map\_menu\_link to give it some depth at least.

```
function MYTHEME_site_map_menu_link(array $variables) {
    $element = $variables['element'];
    $sub_menu = '';

    $element['#attributes']['class'][] = 'menu-' . $element['#original_link']['plid'];
    $menu_id = 'menu-' . $element['#original_link']['plid'];
    $link_depth = 'depth-'. $element['#original_link']['depth'];

    if ($element['#below']) {
      $sub_menu = drupal_render($element['#below']);
    }

    $output = l($element['#title'], $element['#href'], $element['#localized_options']);
    return '<div class="'.$menu_id." ".$link_depth.'"><li>' . $output . $sub_menu . "</li>\n</div>";
}

```

# Answer
> 1 votes
You can use `theme_site_map_box` in your `template.php`!

I've done something similar before where I've changed the H2's to H3's:

Try something like the following in your `template.php`

```
function MYTHEME_site_map_box($variables) {
  $title = $variables['title'];
  $content = $variables['content'];
  $attributes = $variables['attributes'];

  $output = '';
  if (!empty($title) || !empty($content)) {
    $output .= '<div' . drupal_attributes($attributes) . '>';
    if (!empty($title)) {
      $output .= '<h3 class="title">' . $title . '</h3>';
    }
    if (!empty($content)) {
      $output .= '<div class="content"><div class="MYCLASS">' . $content . '</div></div>';
    }
    $output .= '</div>';
  }

  return $output;
}

```

I can't remember off the top of my head the structure of `$content`, but the above code should put an extra div around each section of the site map with the class of `MYCLASS`.

API Docs: `theme_site_map_box()`

# Answer
> 0 votes
Alternatively, you could use menu\_block module to create blocks for each list. Then you can target them individually, mix in other content etc.

> It provides configurable blocks of menu trees starting with any level of any menu. And more!

Kim

---
Tags: navigation
---


# Question
Title: Testing Email locally? Could i reroute email to watchdog?
I'm trying to debug how an email invoice looks in ubercart locally. Mail is not configured on my local machine (ubuntu 11.10).

I really would prefer to debug this locally without sending nagging emails to the stakeholders.

Is there anyway to reroute email output to the watchdog log?

# Answer
> 4 votes
Yes, you can use the Maillog / Mail Developer module.

> Maillog provides an easy possibility to log all Mails for debugging purposes. It's possible to prevent the mails to being sent, so there is no need for an extra mail server to test the mail functionality of other modules or the Drupal core. Additionally you can immediately display the mail through the devel `dpm()` facility.

# Answer
> 1 votes
You could use

http://www.toolheap.com/test-mail-server-tool/

It will listen to port 25 and save emails to files and optionally open them in your local email client

---
Tags: 6, ubercart, emails, testing
---


# Question
Title: Is it possible to alter $form_state before it is passed to user_profile_form_submit?
I have a form posting updates to the user account.
The problem is I need to add some more data to the post object before user\_profile\_form\_submit gets a hold of it.

Is this possible in Drupal 7?

# Answer
> 1 votes
There many ways to alter the $form\_state values. It would be nice if we know what you wanna change so that we can say the best way to do it. Any way the following hooks can help.

* hook\_form\_alter
* hook\_validate
* hook\_form\_submit
    + You can have your own submit function either by overriding the `$form['#submit']` values in hook\_form\_alter or add one to modify the values.

---
Tags: 7, forms, hooks
---


# Question
Title: Unserialize() Error after moving the installation directory
I have just added a repository from git to my Eclipse IDE , setup the database with proper imports and dumps, however getting

```
Error at offset in cache.inc

```

Any suggestions what went wrong and solution.

# Answer
After making a back-up of current db,

Try this in phpMyAdmin or mysql console.

```
TRUNCATE `cache`;
TRUNCATE `cache_block`;
TRUNCATE `cache_bootstrap`;
TRUNCATE `cache_field`;
TRUNCATE `cache_filter`;
TRUNCATE `cache_form`;
TRUNCATE `cache_image`;
TRUNCATE `cache_libraries`;
TRUNCATE `cache_menu`;
TRUNCATE `cache_page`;
TRUNCATE `cache_path`;
TRUNCATE `cache_rules`;
TRUNCATE `cache_token`;
TRUNCATE `cache_views`;
TRUNCATE `cache_views_data`;

```
> 3 votes

---
Tags: views, 7, caching
---


title: Facebook style micro publsher

text:
# Question
Title: Facebook style micro publsher
I have been implemented Facebook style micro publsher in my project and now i can post text/media as like Facebook while updating status. Now i need to create a view that contains all posts from every user in a single page . How can i create a view like that ?

# Answer
> 2 votes
There is a default view to get all statuses **(D7)**

This is the path */admin/structure/views/view/statuses\_all/edit*

# Answer
> 2 votes
There is an default view called **statuses\_all/facebook\_status\_all(D6)** in statuses/facebook\_status(D6) module itself, You can use that one.

When you're enabling FBSMP module it will automatically add FBSMP themed attachment field to all the default views of Statuses/facebook\_status(D6). So that view will list down all the statuses with media(If its available.)

---
Tags: views
---


title: How to fetch group name from query?

text:
# Question
Title: How to fetch group name from query?
I'm using Field group Module, I have created 3 groups with name & ID as given below:

```
Group Name    | Machine ID
Stake Holders | group_sh1
Trends        | group_td1
Organization  | group_org1

```

I want to retrieve the group name in a custom module. By using "ctools" I'm able to retrieve the id of the group, but couldn't get name of the group. Please find the code below for your reference.

```
ctools_include('export');
$objects = ctools_export_load_object('field_group', 'conditions', array(
    'entity_type' => 'node',
    'bundle' => DIGITAL_IQ,
  ));

$object = array_shift($objects);
if ($object && isset($object->data)) {
  dpm(field_group_unpack($object)children);
}

```

> --Result---
> 0 (String, 9 characters ) group\_sh1
> 1 (String, 9 characters ) group\_td1
> 2 (String, 10 characters ) group\_org1

How can I retrieve the group name?

# Answer
> 1 votes
```
//Get the Field information.
$field = field_info_instance('node', 'field_business_challenge', DIGITAL_IQ);

//Obtain group of that field.
$field_group = field_get_field_group($field);

//Get the name of the group from the Lable Attribute.
dpm($field->Lable);

```

There you go, you have the group name.

---
Tags: entities
---


title: Distributed Solr Indexing from Drupal

text:
# Question
Title: Distributed Solr Indexing from Drupal
I want a sharded Solr environment so that I can distribute data and query accordingly. Started two solr instances as described here.

Since Solr doesn't support (fully yet) writing automatically into different Solr instances, I have to do it manually.

I'm trying to do it in the following hook:

```
/* "node" is the module name. */
function node_apachesolr_index_document_build($document, $entity, $entity_type, &$env_id)
{
}

```

Note that I'm trying to change the `$env_id` by making it a reference parameter, since that's what I want to change based on certain logic. When the cron is run, I get the error:

> Warning: Parameter 4 to node\_apachesolr\_index\_document\_build() expected to be a reference, value given in module\_invoke\_all() (line 857 of /var/www/drupal-7.17/includes/module.inc)

since it messes up with existing calls.

Any idea how to workaround this? Thanks.

# Answer
> 1 votes
According to the documentation, the function hook\_apachesolr\_index\_document\_build(), on line 373 of file apachesolr.api.php, is not a reference value, instead directly a variable. So, the code should be:

```
function hook_apachesolr_index_document_build(ApacheSolrDocument $document, $entity, $entity_type, $env_id) {

}

```

Also, from the code you use, I suspect the following possibilities:

1. You are adding the code to the core *node* module, which is never recommended, as one should **never hack core**.
2. If you are adding this code to a custom module, and name that module *node* (as you mentioned in the comment of the code), that will conflict with the core *node* module, and might cause conflicts and break down your code.
3. If you add this code to a custom module (with a different name), then it is a wrong way to implement a hook in custom module. Follow this guide to get started with module development.
Lets say, if you name your module "custom\_search", then you should place this code in the file `custom_search.module`, and implement it in the following way:

```
function custom_search_apachesolr_index_document_build(ApacheSolrDocument $document, $entity, $entity_type, $env_id) {

}

```

Note that, I've replace the *hook* in the function name with the module name "custom\_search"

# Answer
> 0 votes
I am not sure that I can give a complete answer , However have a look on the search results and modules available, this may give you an idea/hint,

> 1) An advanced option to allow configuration of "shards". This allows Solr to do a distributed search across several cores. A Filter by site Facet. Addition of the site host onto the extra result information (the small text under each result).

> Multisite search is made possible by having many sites share an index. Because each "document" is stored in the index with a site and a hash field, it is possible to filter by site or hash, and thus return results from just one site, or from all of the sites sharing an index.

I will try to update you on this after digging more into the module.

---
Tags: 7, search
---


title: Best way to deal with long list

text:
# Question
Title: Best way to deal with long list
I've an entity called "guy" with a field "location" and i've 9-10.000 location that i want to reference. I must use a simple list (1|bla, 2|blabla) or an entity reference field that target the location entity? I need the autocomplete function but drupal is very slow with a great number of location. But i don't know if i can load a list of 9-10k lines. I don't wont to use taxonomy. To speed up the autocomplete, how i can create a list of frequently selected location?

# Answer
**I dont think there is a module you can use.**

The form will contain an element such as

```
<?php
  $form['city'] = array(
    '#type' => 'textfield',
    '#title' => 'City',
    '#maxlength' => 128,
    '#autocomplete_path' => 'cities/autocomplete',
  );
?>

```

Addition to hook\_menu

You must add #autocomplete\_path to your hook\_menu function.

```
<?php
    function cities_menu(){
    ...
    // path with autocomplete function for cities
    $items['cities/autocomplete'] = array(
      'title' => 'Autocomplete for cities',
      'page callback' => '_cities_autocomplete',
      'access arguments' => array('use autocomplete'),  //or whatever permission makes sense
      'type' => MENU_CALLBACK
    );
    return $items;
?>

```

Make a call to the Database.

```
<?php
/**
 * autocomplete helper
 * $string = string for search
 */
function _cities_autocomplete($string) {
  // Fetch most used cities.
  $matches = array();
  $result = db_select('cities', 'c')
    ->fields('c', array('city'))
    ->condition('city', '%' . db_like($string) . '%', 'LIKE')
    ->execute();

  // save the query to matches
  foreach ($result as $row) {
    $matches[$row->city] = check_plain($row->city);
  }

  // Return the result to the form in json
  drupal_json_output($matches);
}
?>

```

Make sure your autocomplete handler has appropriate menu permissions set on it,

From : Textfield that uses autocomplete
> 1 votes

---
Tags: 7, entities, performance, ajax
---


# Question
Title: Drupal module to hide part of body field initially
I'm having trouble finding results for this because there are so many conflicting search terms.

I have a content type in which I want to hide most of the Body to start, but add a Read More type of link which would just use javascript to reveal the rest of the body.

Here is an example of what I'm talking about (I'm converting this site to drupal):

http://www.inadaydevelopment.com/app-10biiFinancialCalculator-iOS.php

I'm having trouble searching for something because "Read More" returns a ton of results about the standard Read More link.

Do you know of a module that will let me do this easily?

# Answer
You can do this using a jQuery plugin. See this drupal/stackoverflow response.

The jquery project page for readmore. Other jquery modules can do this as well such as Expander. Expander looks newer and more supported (off hand).

You could just add this file to your site's theme folder and theme info file. You probably want to not use `Teasers` anywhere and just rely on the JS readmore links for a CSS selector targeting your node body content. Your theme may have a more specific selector.
> 0 votes

---
Tags: 7
---


title: Module for creating "entity edit" form?

text:
# Question
Title: Module for creating "entity edit" form?
Is there a module that will take an entity machine name and optionally id as input, and generate a suitable edit form as output?

# Answer
If you want to create or edit a reference entity in a node add/edit form then you can use Entity Connect module.

If you want to have a separate page which `will take an entity machine name and optionally id as input` then you can have a look at the code in this module and build on that.

You may also take a look at Inline entity Form
> 1 votes

---
Tags: entities
---


# Question
Title: How do I show nodes/articles with specific taxonomy on a page?
Maybe the title is not appropriate, so please dont hesitate to change it or give suggestions for it.

Here's how our Drupal site is done:

A vocabulary called "`PAA`". With this vocabulary there are many terms organized like this:

```
PAA
  |
  \-- MainTerm01
  |   |
  |   \-- SubTerm01
  |   |
  |   \-- SubTerm02
  |   |
  |   ...
  |
  \-- MainTerm02
      |
      \-- SubTerm03
      |
      \-- SubTerm04
      |
      ...

```

Then we have tons of articles that are associated with only one `MainTermXX` and only one `SubTermXX` (whatever `XX` is). Here's what we'd like to do: make a page where we can search for a term (either `MainTermXX` or `SubTermXX`) and display all articles that are associated with the term.

My question is: is there a way to do this easily (= is this native in Drupal, just configuration) or will I have some work to do about this?

# Answer
You can use Views for building the output of the page and filtering according to the search query (that is called "exposed filter" in views).

To get familiar with Views and see all what you can do with them, check out Nodeone library of videos on Vimeo.
> 4 votes

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


title: Which table should I query?

text:
# Question
Title: Which table should I query?
On the parent term page, I want to get all the nodes belonging to the parent term page and its children term. I need to output the node title, a field I created, and the node summary.

Which tables should I query? Which condition should I use?

```
$query = new EntityFieldQuery();

$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'product')
  ->propertyCondition('status', 1)
  // field_fenlei is the category field name.
  ->fieldCondition('field_fenlei', 'tid', arg(2))
  ->range(0, 10);

$result = $query->execute();

if (isset($result['node'])) {
  $nids = array_keys($result['node']);
  $nodes = entity_load('node', $nids);
  echo $nodes->title;
}

```

# Answer
> 0 votes
You want to specify that you searching for nodes first (and optionally by your content type), and then filter by term:

```
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
->entityCondition('bundle', 'YOUR_CONTENT_TYPE_HERE')
->fieldCondition('field_game', 'tid', 5);

$result = $query->execute();
$nids = array_keys($result['node']);
$nodes = entity_load('node', $nids);

```

How to use EntityFieldQuery

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


# Question
Title: Embedded video thumb has been displayed on all overlay windows
I have been created a block to display YouTube videos on my website ,When ever i tried to open admin windows that video thumbnail has been displaying on every overlay windows how can i disable that any suggestions ?

---

Screenshot :

---

# Answer
You could try CSS z-index Property

> **Definition and Usage**
>
> The z-index property specifies the stack order of an element.
>
> An element with greater stack order is always in front of an element with a lower stack order.
>
> Note: z-index only works on positioned elements (position:absolute, position:relative, or position:fixed).

Try setting a `higher` value to the overlay or a `lower` value to the youtube player.
> 0 votes

---
Tags: blocks, nodes
---


title: Drupal 7 CCK number

text:
# Question
Title: Drupal 7 CCK number
As long as I know there is no number field in Drupal 7. All I can see is a List(integer) field. The problem that I'm facing is in sorting with respect to this field in views. I want my content to be sorted numerically not alphabetically. Suppose I have three nodes with field values of 1,8,13. Sorting with views results in the this order: 1,13,8. Any Solution?

# Answer
In the content type while creating the field, if you have selected `List(integer)` then it will sort by the numerical value. If you are sure that you have selected `List(integer)` and sill in the view it is not sorting by numeric value, then the culprits can be

1. You have the display Format as a table and table settings has some other default sorting order.
2. Make sure that in the Sort list in the view, your field is above any other fields used for sorting. By default post data field will be used for filtering.
3. If both of the above steps are verified, then may you have rewritten the field, which is affecting the order.
> 0 votes

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


# Question
Title: Communicating with Drupal from Javascript/Jquery (Drupal 7)
I am trying to create a dynamically populated select list field widget. This widget consists of three Jquery multiple selects. When the user makes a selection from the first select list I need to dynamically populate the contents of the second select list. My problem is that I need to access data stored in Drupal about what should be put in the second list based on the first selection and the only way I can think to access this data is through an ajax call to a Drupal endpoint. Waiting for the return from an ajax call is going to be to slow for a useable widget so I need a better way to access this data stored in Drupal. How should one go about doing this?

# Answer
> 1 votes
You can send variables to your JS with drupal\_add\_js() in the $settings array.

An other way (the dirty one) to do it would be to *print* your data in a hidden div and read it with your JS. (don't hesitate to ask if you need code to do it)

Have fun !

# Answer
> 0 votes
There is a variety of ways to do that:

The drupal way would probably be to read a bit on chaos tools and fork the example for the dependent select box.

What I personally use is the great module knows as Views\_datasource, that allows you to output view content as a json array.

So the workflow goes like this:

You have the first populated select, that you bind its change event. You retrieve the value of the select box and submit it via ajax to a view with a contextual filter rendered through views\_datasource. You retrieve the json reply and populate you second select.

Have fun.

# Answer
> 0 votes
Add the following line in your code/module

```
drupal_add_js(array('myModule' => array('awesome_cms' => 'Drupal-Seven')), 'setting');

```

Then from your jquery access `Drupal.settings.awesome_cms` to get the value `Drupal-Seven`

---
Tags: 7, javascript, entities
---


# Question
Title: Multiple sites routed to one codebase has the subdirectory name as prefix on the links
I am trying to redirect multiple drupal sites to same code base using following htaccess file

```
RewriteEngine on
RewriteCond %{HTTP_HOST} ^(www.)?site.com$ [NC]
RewriteCond %{REQUEST_URI} !^/subdirectory/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ subdirectory/$1
RewriteCond %{HTTP_HOST} ^(www.)?ngeneric.com$ [NC]
RewriteRule ^(/)?$ subdirectory/index.php [L]

```

It workds but, now every URL on the site has its subdirectory infront like

> http://site.com/**subdirectory**/.....

How to fix this?

**More Info:** Domain is routed to `public_html/a/` The drupal site in inside this `a` directory as `public_html/a/b` and I am trying to use multiple sites, so I am getting this problem.

# Answer
> 0 votes
Try to set the `$baseurl` variable in settings.php, at Drupal site directory. Read the documentation around this variable in the settings file.

---
Tags: uri
---


title: convert to db_query and addExpression

text:
# Question
Title: convert to db_query and addExpression
Is there a way convert this static query in a dynamic query?

```
$sql = "SELECT n.nid, n.title, n.created, n.type, n.status, IF((SELECT nid FROM `newsletter_lists` WHERE cid=$cid AND nid=n.nid), TRUE, FALSE) AS included FROM `node` AS n
  LEFT JOIN `newsletter_lists` AS nl ON n.nid = nl.nid";

```

This is what I have, but it throws errors.

```
$query = db_select('node', 'n')
  ->fields('n', array('nid', 'title', 'created', 'type', 'status'))
  ->extend('PagerDefault')
  ->limit(5);

$subquery = db_select('newsletter_lists', 'snl')
  ->fields('snl', array('nid'))
  ->condition('cid', $cid)->condition('nid', `n.nid`)
  ->execute();

$query->addExpression($subquery, 'included');

return $query->execute();

```

# Answer
The problem is that `addExpression()` doesn't take a `SelectQueryInterface` as a parameter, but only a string:

> **$expression:** The expression string. May contain placeholders.

So the best you're going to be able to do is add the expression as a manual string. As the argument description suggests placeholders are fine so you can at least keep a bit of structure.

```
$query = db_select('node', 'n')
    ->fields('n', array('nid', 'title', 'created', 'type', 'status'))
    ->extend('PagerDefault')
    ->limit(5);

$expression = 'IF((SELECT nid FROM `newsletter_lists` WHERE cid= :cid AND nid = n.nid), TRUE, FALSE)';

$query->addExpression($expression, 'included', array(':cid' => $cid));

return $query->execute();

```
> 1 votes

---
Tags: database
---


title: View and fixed operator

text:
# Question
Title: View and fixed operator
I've made a view that contains a filter that the visitor can change. The problem is that it give the possibilities to filter trough a combobox:

* Is equal to
* Is not equal to
* Contains
* Contains any word
* Contains all words
* Starts with
* Does not start with
* Ends with
* Does not end with
* Does not contain
* Length is shorter than
* Length is longer than
* Regular expression

***I don't want them***! I just want the user to see an input field and click "ok" (something like that). And the search would be "Contains all words".

How to do this?

# Answer
> 2 votes
in your exposed filter, is the "expose operator" option checked ?

This might be the obvious answer.

# Answer
> 1 votes
Just uncheck the "Expose operator" option in the filter settings page, then the user will be forced to use the specific operator that you select.

---
Tags: views, entities, search
---


# Question
Title: How do I get computed column using db_select?
I require sum(points)? Any help on what to add in the sample code given below?

```
$query = db_select('digitaliq_question_points','n')
  ->fields('n',array('points'))
  ->condition("node_id", $node->nid, '=')
  ->condition('n.fld_group', $fields, 'IN');

$points = $query->execute()->fetchAll();

```

# Answer
> 9 votes
You can make use of the `addExpression()` method:

```
$query = db_select('digitaliq_question_points','n')
  ->fields('n',array('points'))
  ->condition("node_id", $node->nid, '=')
  ->condition('n.fld_group', $fields, 'IN');

$alias = $query->addExpression('SUM(points)', 'sum_of_points');

$points = $query->execute()->fetchAll();

```

Obviously that might need to change slightly based on your return value/grouping requirements but that's the method you're looking for.

---
Tags: database
---


# Question
Title: The version of CKEditor could not be detected
> **Possible Duplicate:**
> CKEDITOR not working Drupal 7

When I try to enable CkEditor, I get the following error.

I have already extracted the files in sites/all/libraries/ckeditor.

Is there any problem with the version of this module? How can I fix this?

I have already read Ckeditor doesn't work.

# Answer
> 4 votes
What you need to do after installing the module is go to http://ckeditor.com and download the latest version. Then uncompress the contents of the 'ckeditor' directory of the downloaded file to this folder 'libraries/ckeditor/ckeditor'.

**Installation steps**

1. Unzip the module files to the "sites/all/libraries" directory. It should now contain a "ckeditor" directory.
2. Download standalone CKEditor from http://ckeditor.com/download. Unzip the contents of the "ckeditor" directory from the installation package to the "sites/all/libraries/ckeditor/ckeditor" directory. Note: you can skip uploading the "\_samples" and "\_source" folders.
3. Enable the module in the "Administration panel \> Modules \> User Interface" section.
4. Grant permissions for using CKEditor in the "Administration panel \> People \> Permissions" section. Note: In order to enable the file browser, refer to the "Installing CKFinder" section.
5. Adjust CKEditor profiles in the "Administration panel \> Configuration \> Content Authoring \> CKEditor" section. Profiles determine which options are available to users based on the input format system.

# Answer
> 1 votes
I couldn't get CKEditor 4 working having downloaded it and used it on a clean install so follow the upgrade advice above.

Read the instructions in the WYSIWYG config as to the path, it should be:

```
sites\all\libraries\ckeditor

```

Note: the if you extract to this folder you will get

```
sites\all\libraries\ckeditor\ckeditor

```

which obviously won't work as the ckeditor.js file is in the wrong place!

---
Tags: wysiwyg
---


# Question
Title: Change the heading User Accounts in user Registration Page
I am trying to change the heading in User Registration Page from User Account to Registration.

I tried pre-processing, but in the page variable title is empty and I can only see rendered html.

I also tried using the following code in the settings.php file, but it doesn't seem to work.

```
$conf['locale_custom_strings_en'][''] = array(
  'USER ACCOUNT' => 'Registration',
  'Add new comment' => 'post new comment',
);

```

# Answer
> 3 votes
"User account" is the title that an anonymous user see for the "Create new account," "Log in," and "Request new password" pages. Replacing "User account" with "Registration" using `$conf['locale_custom_strings_en']` would cause the string to be replaced in every place where "User account" is used, which is not correct.

The solution is to replace the title callback used for user with another title callback. Create a custom module, or add the following code to the custom module you are already using.

```
function mymodule_menu_alter(&$items) {
  if (isset($items['user'])) {
    $items['user']['title callback'] = 'mymodule_user_title';
  }
}

function mymodule_user_title() {
  if (!user_is_logged_in()) {
    switch (current_path()) {
      case 'user':
      case 'user/login':
        return t('Log in');
      case 'user/register':
        return t('Create new account');
      case 'user/password':
        return t('Request new password');
      default:
        return t('User account');
    }
  }
  else {
    return t('My account');
  }
}

```

The code I used for `mymodule_user_title()` is exactly the same code used by Drupal 8 in its user\_menu\_title().

Other solutions, such as using the String Overrides module don't work too, as they replace the string independently from the context, which is important in this case. Users who are in the page for requesting a new password should not read "Register" as title because they are not registering.

---
Tags: 7, users, theming
---


# Question
Title: Block visible only to the user who created it
Is there any module that allows a block to be seen only by the user who created it, and not to any user with the same role?

# Answer
You can use block visibility settings PHP code to check for specific users.

Please find the sample php code below.

```
<?php
global $user;
$allowed = array('moderator','administrator'); // Allowed Roles
$allowed_uids = array(1, 5, 10); // 1, 5, 10 are user id's which you want to allow
$valid=FALSE;
foreach($user->roles as $role){
  if(in_array($role, $allowed) && in_array($user->uid, $allowed_uids)) {
    $valid=TRUE;
  }
}
return $valid;
?>

```

See the screen show below where you need to write above code.
> 3 votes

# Answer
There isn't any module that shows the block only to the user who created it.

Drupal doesn't record who has created a block. Even supposing a module would record such information to decide who can view a block, that module would not be much useful, as the user who can add a new block in a Drupal site are already restricted to the users with the permission to administer blocks, which is not a permission you normally give to any user with an account on a Drupal site.
> 2 votes

---
Tags: blocks
---


title: what's wrong with the query code?

text:
# Question
Title: what's wrong with the query code?
```
    $query = db_select('node', 'n')
                ->join('field_data_field_fenlei', 'c', 'n.nid = c.entity_id')
                ->join('taxonomy_term_hierarchy', 'th', 'c.field_fenlei_tid = th.tid')
                ->join('node_type', 'nt', 'n.type = nt.type')
                ->condition('n.type', 'product')
                ->condition( db_or()
                    ->condition('th.tid', arg(2), '=')
                    ->condition('th.parent', arg(2), '=') )
                ->fields('n', array('nid'))     // select nid field only so that node_load() will be called later
                ->extend('PagerDefault')        // this adds the pager
                ->limit(5);

$result = $query->execute();

```

product is the content type. field\_fenlei is the category machine name . which is a select list, contains all the term.

i put the above code in the term template page file, the page shows unnormal(the page doesn't load the header part ....). there is something wrong with the query code?

is there a way to test whether the query code right or not?

# Answer
Ohhh I've just realised why you're getting an error...`join()` isn't chainable, it returns the created alias to the joined table.

Try this instead:

```
$query = db_select('node', 'n')
  ->condition('n.type', 'product')
  ->condition( db_or()
    ->condition('th.tid', arg(2), '=')
    ->condition('th.parent', arg(2), '=') )
  ->fields('n', array('nid'))
  ->extend('PagerDefault')        // this adds the pager
  ->limit(5);

$query->join('field_data_field_fenlei', 'c', 'n.nid = c.entity_id');
$query->join('taxonomy_term_hierarchy', 'th', 'c.field_fenlei_tid = th.tid');
$query->join('node_type', 'nt', 'n.type = nt.type');

$result = $query->execute();

```
> 1 votes

---
Tags: 7
---


# Question
Title: Change position of submit button on form
This is my code:

```
function feature_contact_form_form_alter(&$form, $form_state, $form_id)
{
if ($form_id == 'contact_form_node_form') {
  $form['field_user_agent']['#type'] = 'hidden';
  $form['field_ip_address']['#type']      = 'hidden';
  $form['buttons']['submit']['#weight'] = -15;
}
}

```

I am using Drupal 6. I am trying to change the position of the submit button. I am using conditional fields also on this content type. weighting is not changing the position.

# Answer
> 0 votes
I added the form elements submit buttons onto the node add/edit panel in the correct place, which solved my problem.

---
Tags: 6, forms
---


# Question
Title: Is it possible to have language specific content?
I am working on a Drupal 7 site that is currently in English only. We are now looking at adding additional language support and so far I've got the hang of content translation using i18n.

We currently have a news section composed of articles for each story. Is it possible to write language-specific articles? E.g. if there is a French-only news story, it won't appear on the English language site.

# Answer
> 1 votes
We managed to find a solution and it involved using view filters.

In case it is useful for anyone else, you can do this by selecting Edit View in the top right hand corner of the view. Click on the Add button next to Filter Criteria and then choose "Content translation: Language".

Alan

# Answer
> 0 votes
You can have this feature in Drupal, but I recommend to start at Multilingual Guide of drupal.org

---
Tags: i18n-l10n
---


# Question
Title: Issue with module's hook_uninstall (not uninstalling db entries)
I have a custom Drupal 6 module (based on this issue) that puts some custom date and time formats into the `date_format_types` table and then can be accessed from `/admin/settings/date-time/formats`. This works nicely but I'd like to remove these from that table if the module gets uninstalled.

In my module's .install file, I tried this code:

```
<?php

/**
 * Implementation of hook_uninstall().
 */
function eventdates_custom_uninstall() {
  db_query("DELETE FROM {date_format_types} WHERE type LIKE 'eventdates_custom_date_%'");
}

```

This does not seem to work and the entries that had been added do not get removed from the date\_format\_types table when I uninstall the module but I am pretty sure I have the query correct.

# Answer
`%` is used as the placeholder marker for D6 queries, so you need to escape it with another `%`:

```
db_query("DELETE FROM {date_format_types} WHERE type LIKE 'eventdates_custom_date_%%'");

```

As a test I just added the following to the date\_format\_types table:

And then ran this query from the devel/php page:

```
db_query("DELETE FROM {date_format_types} WHERE type LIKE 'eventdates_custom_date_%%'");

```

And both rows were deleted:
> 5 votes

---
Tags: 6, database, datetime
---


title: Menu synchronization

text:
# Question
Title: Menu synchronization
I am building a site with main-menu at header and side-bar-menu. For each main-menu entry there will be some sub-menus. And same sub-menu will be displayed into side-bar-menu according to the portal we are in. Is it any way (or module) to synchronized main-menu-\>sub-menu and side-bar-menu so that in case we need to change menu, we can change it in one place and reflects in main-menu and side-bar-menu.

Thank you.

# Answer
> 2 votes
Your main menu can be 1 level deeps links to content. You just maintain these links as your top level content links as needed in the Menu configuration page.

For each main-menu item, make a new Menu where you actually set the link from your node edit pages.

Use MenuBlock and like the Context module (or just default the Block UI, eww) set each sidebar menublock to appear for the appropriate main-menu url path.

**-- OR TRY --**

You can try to make main-menu your site tree of all links, then use 1 menu-block set to 2-level deep starting point based on the url path.

I usually try to do the 2nd option .... then find its inflexible at some point and need a collection of menus and menu\_blocks as I first described which from experience works better. Especially for cross-linked content (you may get the wrong menu block in the 2nd approach, for cross linked content as it shows the first menublock that menu\_block finds the link within).

# Answer
> 1 votes
You want the Taxonomy menu module to do this. Here is a quote about it (from the module's project page):

> Transforms your taxonomy vocabularies into menus with ease!
>
> **Features**:
>
> * Custom Menu per vocabulary
> * Uses the default taxonomy term path or custom paths
> * Integrate with Views
> * Integrate with Pathauto: use URL/path aliases
> * Does not interfere with other menu modules

---
Tags: 7, routes
---


# Question
Title: New image field type for Articles only displaying on the article node itself, not on taxonomy or custom view pages
I am having some issues with custom field content only displaying on the individual node. I have created a new field called field\_second\_image for the Article content type. I am calling it right under the regular field\_image with print render($content\['field\_second\_image'\]); in my node--article.tpl.php file. On the actual article node both images display properly. However, on a taxonomy list page or the custom article view page I have created, the second image does not show up. I think this relates to the general issue I've been having getting custom field content to display on pages other than the individual node page. Is there something I'm completely missing about getting this content to appear on other pages? Any help would be greatly appreciated, thank you.

# Answer
> 0 votes
Yes, the concept is `view_modes`. See this documentation page as an introduction.

`node--article.tpl.php` is used to show the `Default` view mode of a node. The related taxonomy page(s) for terms lists content out by default using the `Teaser` mode. This view mode is usually a succinct version of your complete node fields (sometimes showing a body teaser, and fewer fields).

Some modules to help you create new "view modes" of your content and easily customize how and what is shown are for instance (a small example list, by NO MEANS all of the possabilities, nor are these necessarily the best options):

# Answer
> 0 votes
@Tenken the solution actually ended up being much simpler. I just had to go under the Manage Display tab and enable the new field to be visible in the teaser. Thanks for those links though I think they'll prove useful in the future.

---
Tags: entities
---


# Question
Title: slideshow images for one specific view, with alot of fields
I have a product content type which has like 10 fields, so I want to show it in my main page with view, the problem is, I want to show it's multiple images as a slideshow, It's not only images that I can use views\_slideshow or nivo\_slider or any other slideshow modules, I only want the images to be shown as slideshow, along other text-fields of my node.

I would really appreciate any help, thanks

# Answer
> 1 votes
you can use Field Slideshow. If it's not a good solution, another one would be to create 2 views (one slideshow with only the images, one normal with all the other fields) and, with CSS, position one over the other.

Have fun !

---
Tags: views, 6, javascript
---


# Question
Title: Pathauto alias produces inconsistent aliases
I have a content type with its own Pathauto pattern `studios/[node:title]`. What could be the reason that the alias of the node entitled "Studio A" is `studios/studio`, whereas for "Studio B" (for the same language) - `studios/studio-b`. The latter being the desired shape of course. I tried to resave the node, I tried to bulk delete aliases and re-generate them - all to no avail.

# Answer
Check settings in `Administration » Configuration » Search and metadata » URL aliases` there is a *Strings to Remove* like this:

> a, an, as, at, before, but, by, for, from, is, in, into, like, of, off, on, onto, per, since, than, the, this, that, to, up, via, with

thats why your **A** is removed i think.
> 4 votes

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


title: Use jCarousel with an Image field?

text:
# Question
Title: Use jCarousel with an Image field?
The jCarousel plugin looks like it's mostly used with Views, but I'd like to use it (or something like it) for a simple Image field which has multiple images in it.

Do you know of a way to do this or another module which behaves this way?

# Answer
> 2 votes
For nodes image field you can use Field Slideshow module with your JCarousel it solves your problem

# Answer
> 0 votes
Views slideshow will do the job for you:

> Views Slideshow can be used to create a slideshow of any content (not just images) that can appear in a View. Powered by jQuery, it is heavily customizable: you may choose slideshow settings for each View you create.

---
Tags: 7, media
---


title: Set Taxonomy Description via Rules

text:
# Question
Title: Set Taxonomy Description via Rules
Question: How can I access a taxonomy's description in the "Rules" module? When I create a new taxonomy entity I can only set the name of the term, I'd like to also add the term's description.

Goal (in case I'm doing this entirely wrong!): Anonymous submission of new taxonomy terms with a description, for approval by a role. When node type of "new term" is approved, it copes it to a taxonomy vocabulary and then deletes the original node.

# Answer
> 2 votes
in Rules, after your Action **Create a new entity** (of type taxonomy term), when you set a new one, **Set a data value**, find *the entity you just created* -\> **Description** .

---
Tags: taxonomy-terms, rules, workflows
---


# Question
Title: changing a MySQL query to a drupal query any ideas
**I'm trying to change the following query to a drupal db\_query:**

```
SELECT first_name, SUBSTR(first_name,1,3) AS firstname_substr FROM civicrm_contact WHERE id != 'NULL' ;

```

**I have tried this, but its not working:**

```
$firstname_substr = $query->addExpression('SUBSTRING(cc.first_name,1,3)','cc.firstname_substr');

```

**Below is the function I am trying to add it to:**

```
function search_pcp($name, $from = 0, $count = 5){

  $query = db_select('civicrm_pcp', 'pcp');
  $query -> join('civicrm_contribution_page','cp', 'pcp.page_id = cp.id');
  $query -> join('civicrm_contact','cc','pcp.contact_id = cc.id');
  $query -> addJoin('LEFT OUTER','civicrm_entity_file','cef', 'cef.entity_id = pcp.id');
  $query -> addJoin('LEFT OUTER','civicrm_file','cf', 'cef.file_id = cf.id');
  $query -> condition('pcp.is_active','1','=');
  $query -> condition('cp.is_active','1','=');

  $db_or = db_or();
  $db_or->condition('cc.first_name',  $name, 'like');
  $db_or->condition('cc.last_name',  $name, 'like');

  **//$db_or->condition($firstname_substr, $name);**

  $query -> condition($db_or);

  return $query->execute();

}

```

# Answer
I believe you need to change

```
$firstname_substr = $query->addExpression('SUBSTRING(cc.first_name,1,3)','cc.firstname_substr');

```

to

```
$query->addExpression('SUBSTRING(cc.first_name,1,3)','firstname_substr');

```

and

```
$db_or->condition($firstname_substr, $name);

```

to

```
$db_or->condition('firstname_substr', '%'. db_like($name) . '%', 'like');

```

So it will look like this:

```
function search_pcp($name, $from = 0, $count = 5){

  $query = db_select('civicrm_pcp', 'pcp');
  $query->join('civicrm_contribution_page','cp', 'pcp.page_id = cp.id');
  $query->join('civicrm_contact','cc','pcp.contact_id = cc.id');
  $query->addJoin('LEFT OUTER','civicrm_entity_file','cef', 'cef.entity_id = pcp.id');
  $query->addJoin('LEFT OUTER','civicrm_file','cf', 'cef.file_id = cf.id');
  $query->condition('pcp.is_active','1','=');
  $query->condition('cp.is_active','1','=');

  // changed cc.firstname_substr to just firstname_substr
  $query->addExpression('SUBSTRING(cc.first_name,1,3)','firstname_substr');

  $db_or = db_or();
  $db_or->condition('cc.first_name',  $name, 'like');
  $db_or->condition('cc.last_name',  $name, 'like');

  // corrected the condition statement
  $db_or->condition('firstname_substr', '%' . db_like($name) . '%', 'like');

  $query -> condition($db_or);

  return $query->execute();

}

```
> 2 votes

---
Tags: database
---


# Question
Title: using xhprof in drupal 6 to monitor a cron task and display in the XHProf runs page
I'm trying to profile a specific cron task in drupal 6 to check the function calls made and what consumes the maximum time and decided to use the XHProf module which I've never used before. I've got the module successfully installed and able to get the page loads profiled and listed in admin/reports/xhprof.

But to get my cron task to be profiled and listed in it I'm pretty clueless and tried out a few things from what I could gather from PHP.net but beyond coding

```
xhprof_enable();
echo "<h2>ENABLED</h2>";
// the code block I wish to profile
$xhprof_data = xhprof_disable();
echo "<pre>";
print_r($xhprof_data);
echo "</pre>";

```

by checking the internet. The `$xhprof_data` does contain the necessary info array. But I'm not able to get the slightest hint of how this data that's printed could be formatted and displayed like the page loads which get profiled out of the box. Any help on this is greatly appreciated.

# Answer
I haven't used the D6 version before but rummaging through the code I think something like this will work:

1st bit (taken from `xhprof_shutdown_xhprof()`)

```
$namespace = variable_get('site_name', '');  // namespace for your application
$xhprof_data = xhprof_disable();

// Path to save file. Leave empty to use a default
$xhprof_data['path'] = isset($_GET['q'])?$_GET['q'] : '';
$class = variable_get('xhprof_default_class', 'XHProfRunsFile');
$xhprof_runs = new $class();
$run_id = $xhprof_runs->save_run($xhprof_data, $namespace);

```

2nd bit (taken from `xhprof_display_page()`)

```
drupal_add_css(drupal_get_path('module', 'xhprof') . '/xhprof.css');
$html = xhprof_display_run(array($run_id), NULL);

// Do what you need to with $html to get it out to the screen

```
> 1 votes

---
Tags: 6, debugging
---


title: Instr() function on drupal

text:
# Question
Title: Instr() function on drupal
I need a funtionality for search tags from a textarea (drupal form), I make it from sql, then, mysql have this function: https://dev.mysql.com/doc/refman/5.0/en/string-functions.html I believe that oracle/pql does have same function.

```
select * from cms_tags ct
 where instr('Americana Abstract Art Art Antique Jewelry Antique Jewelry Jewelry', ct.name);

```

How can I use that query in drupal way? using db\_select() or something else.

# Answer
> 3 votes
A plain `db_query()` might be easier for this particular query, but if you want to use `db_select()` you can make use of the `SelectQuery::where()` method:

```
$string = 'Americana Abstract Art Art Antique Jewelry Antique Jewelry Jewelry';

$query = db_select('cms_tags', 'ct')
  ->fields('ct')
  ->where('INSTR(:string, ct.name)', array(':string' => $string));

```

# Answer
> 2 votes
Just run it through db\_query().

Try this:

```
$result = db_query("SELECT * FROM {cms_tags} ct WHERE INSTR('Americana Abstract Art Art Antique Jewelry Antique Jewelry Jewelry', ct.name);")->fetchAll());
print_r($result);

```

---
Tags: database
---


# Question
Title: Ajax Function jquery Fails to send data Drupal 7
I am in the process of converting Drupal 6 module to Drupal 7.
i have a problem of Passing php data to Ajax.
The function should display if a speaker on or off by interchanging icons, when clicked by using (toggle function).
whats i have discovered is that this part `$.ajax()` doesnt work, while in Drupal 6 it works.
below is the code.

`longa.module` file:

```
  //hook menu
  function longa_menu(){
  $items=array();
  $items['longa/set_speaker_state'] = array(
   'page callback' => 'longa_set_speaker_state',
   'access arguments' => array('longa talk'),
   'type' => MENU_CALLBACK,
  );
  return $items;
}
 //the callback
 function longa_set_speaker_state($speaker_state) {
  global $user;
  $_SESSION['longa_speaker_state'] = $speaker_state;
  user_save($user, array('longa_speaker_state' => $speaker_state));
 }

```

`longa.js` file:

```
(function($){
 $(document).ready(function(){
  if (Drupal.settings.longa_module.has_audio ==1){
  im_flash_player_listener.onInit = function(){
    this.position = 0;
  };
  if ($('#im-console-speaker-icon-on').css('display') == 'none') {
    is_muted = 1;
  }
  else {
    is_muted = 0;
  }
  $('#im-console-speaker-icon-on').click(function() {
    set_speaker_state(1);
    is_muted = 1;
    //alert('You clicked the speaker');
    $('#im-console-speaker-icon-on').toggle();
    $('#im-console-speaker-icon-off').toggle();
    });
  $('#im-console-speaker-icon-off').click(function() {
    set_speaker_state(1);
    is_muted = 0;
    $('#im-console-speaker-icon-on').toggle();
    $('#im-console-speaker-icon-off').toggle();
    });
  }

 });
})(jQuery);

 function set_speaker_state($speaker_state) {
  if (Drupal.settings.longa_module.has_perms ==0) {
   return;
  }
 var sendurl= url_prefix + 'longa/set_speaker_state/' + $speaker_state;
  //alert(sendurl);
   $.ajax({
   type: 'GET',
   url: sendurl ,
   dataType: 'json',
   data: 'js=1'
   /**success: function(xhr) {
    alert('sent successfully');
    },
    error:function(xhr) {
   alert('error occured');
   }*/
 });
}

```

I will appreciate for any help.

# Answer
> 1 votes
In function set\_speaker\_state() , the $ symbol doesn't recognized, you must put set\_speaker\_state() function into:

```
(function($, window, undefined){
 // here!
})(jQuery, window);

```

# Answer
> 0 votes
Finally i got it working...i just replaced  `$.ajax with jQuery.ajax` and bum, everything works.

---
Tags: 7, ajax, javascript
---


# Question
Title: How to slow down migrate? Cloud Files can't keep up
I'm using migrate to import 2800 blog posts. Each have a header image which is getting imported. I'm using Rackspace Cloud Files as my CDN so the system is copying the image files up to Rackspace Cloud Files, but after it's been running for awhile I start getting this error:

> (/home/drupal/html/sites/all/libraries/rackspace/php-cloudfiles/cloudfiles.php:608) Invalid response: (curl error: 35) error:02001018:system library:fopen:Too many open files: Failed \[error\] to obtain valid HTTP response.

My -guess- is that the migrate is working too quickly and the file transfers are happening in parallel or something and I'm hitting a limit on the number of open files for Rackspace. I'm not exactly sure.

I'd like to try adding a delay in between each node. There are only 2800 and I can let it run for a little while, so I don't mind the delay as long as it'll let me complete the migrate.

# Answer
In your migration scripts you can use either prepare() or complete() (http://drupal.org/node/1132582) and add in sleep(). It's a hacky solution but it should give you enough time between processing each row for Rackspace to catch up.

```
public function prepare($node, stdClass $row) {
  sleep(30); //wait for 30 seconds
}

```
> 2 votes

# Answer
I discovered the true problem (although I'm still accepting the other answer because my question was specifically about slowing the migration down).

I believe there is a bug in the rackspace cloudfiles api which causes connections to not be closed properly. In normal, web-based, circumstances this isn't a problem because at the end of the processing all of the connections are closed and you never usually open enough connections to have a problem.

However, I'm running the migration via drush from the command line which means the process isn't ending for a VERY long time after A LOT of connections and eventually I hit the limit for the max number of open "files."

Please see this question for the solution I used to avoid the problem entirely: Migrate with Cloud Files fopen:Too many open files
> 0 votes

---
Tags: 7, migrations
---


# Question
Title: Migrate with Cloud Files fopen:Too many open files
I'm using migrate to import 2800 blog posts. Each have a header image which is getting imported. I'm using Rackspace Cloud Files as my CDN so the system is copying the image files up to Rackspace Cloud Files, but after it's been running for awhile I start getting this error:

> (/home/drupal/html/sites/all/libraries/rackspace/php-cloudfiles/cloudfiles.php:608) Invalid response: (curl error: 35) error:02001018:system library:fopen:Too many open files: Failed \[error\] to obtain valid HTTP response.

What is causing the problem?

# Answer
I believe there is a bug in the rackspace cloudfiles api which causes connections to not be closed properly. In normal, web-based, circumstances this isn't a problem because at the end of the processing all of the connections are closed and you never usually open enough connections to have a problem.

However, I'm running the migration via drush from the command line which means the process isn't ending for a VERY long time after A LOT of connections and eventually I hit the limit for the max number of open "files."

This isn't a perfect solution, but it works even if it's hackish.

```
class MyArticleMigration extends BasicExampleMigration {
    public function __construct($rangeStart = 0) {
        parent::__construct();

        // code to set up the query where I pull my source data from the database.
        $query->range($rangeStart, 35);

        // rest of the code...
    }
}

class MyArticle0Migration extends MyArticleMigration {
    public function __construct() {
        parent::__construct(0);
    }
}

class MyArticle1Migration extends MyArticleMigration {
    public function __construct() {
        parent::__construct(200);
    }
}

class MyArticle2Migration extends MyArticleMigration {
    public function __construct() {
        parent::__construct(400);
    }
}

// etc...

```

Then on the command line I just run:

```
drush migrate-import MyArticle0Migration
drush migrate-import MyArticle1Migration
drush migrate-import MyArticle2Migration
drush migrate-import MyArticle3Migration

```

etc...
> 0 votes

---
Tags: 7, migrations
---


# Question
Title: Add an item to a list for Rules and References
I have a Node Reference in Users.

When I set Add an item to a list with Node identifier for some event, it doesn't add. It looks like this

```
Add an item to a list
Parameter: List: [account:field-badges], Item to add: 28

```

Set a data value works with comma separated list.

# Answer
> 2 votes
The "add an action" form says: "To make entity fields appear in the data selector, you may have to use the condition 'entity has field' (or 'content is of type')."

My field was in the data selector but the item was not added by the action.

I changed the action to a rule with a condition "entity has field" as requested, the field being the one I wanted to add a value to. Then I recreated the action in the actions area.

This was the solution for me. Hope this helps.

# Answer
> 0 votes
I have had problems in the pass with setting a variable with Actions.

Try this:

1. Add \[new\] Action -\> Add a variable -\> Integer -\> 28 -\> label: badge\_number & machine\_name:variable\_badge\_number
2. Inside your 'Add an item to a list' action, click 'Switch to data selection' and change 28 to the new variable. I believe when done, the data selector textfield should read 'badger-number'

---
Tags: 7, nodes, rules
---


# Question
Title: Fatal error: Failed opening required file
I am quite new in Drupal. When installing Kickstart module in a Acquia based Drupal 7 setup on a localhost, I got this message. I looked on the internet and saw a lot of answers, but it didn't help me. It seems the plugins.inc file is fine, but I can't do anything now.

> Fatal error: require\_once() \[function.require\]: Failed opening required '/Users/aztem/Sites/acquia-drupal/sites/all/modules/panels/plugins/export\_ui/panels\_layouts.inc' (include\_path='.:/Applications/acquia-drupal/common/pear:/usr/lib/php') in /Users/aztem/Sites/acquia-drupal/sites/all/modules/commerce\_kickstart/modules/contrib/ctools/includes/plugins.inc on line 475

# Answer
Commerce Kickstart isn't a module, it's an installation profile. If you want to add Commerce to your site, try install using drush, or just load all the modules manually.

drush dl commerce

Using the drush command will install Ubercart essentially, and you can setup commerce that way.
> -1 votes

---
Tags: commerce
---


# Question
Title: Responsive Images Not Scaled-Down Properly in Omega Theme just on Firefox
I'm building a responsive site using the Omega theme, and Adaptive Image Styles. So, in my Firefox 16.0.2 (Mac) browser, images that are scaling down look very poor quality as they are scaled down. If I take the same image out of Drupal and scale it in the same browser, it looks fine; in any other browser, it looks fine. Images seem to be using proper CSS (`max-width:; height:auto;`).

Check out this snapshot. Is it a bug in my browser or where does the issue exist?

# Answer
What kind of Mac are you using? For example, I have a Retina Mac. Firefox doesn't support Retina displays, so things generally look fuzzier in Firefox than say Chrome.

Also, if the responsiveness is aimed towards mobile devices, wouldn't it be better to test on those? You probably won't have a user with a desktop window of 600px wide. ;)
> 2 votes

---
Tags: media, theming
---


# Question
Title: How do I remove the inserted a span tag in an href parameter when using Full Calendar and Devel Themer
When devel\_themer is active inside of a Fullcalendar formated View, links contain the span tag. See below in the href parameter. This however does go away when I disable devel\_themer and clear cache.

```
<a unselectable="on" href="/%3Cspan%20thmr%3D%27thmr_73%27%20class%3D%27devel-themer-wrapper%27%3Enode/8%3C/span%3E" class="fc-event fc-event-skin fc-event-hori fc-event-draggable fc-corner-left fc-corner-right fc-event-default field-performance-dates fc-event-field-field-tic-performance-dates ui-draggable" style="position: absolute; z-index: 8; left: 558.667px; width: 104px; top: 139px; -moz-user-select: none;">
<div class="fc-event-inner fc-event-skin">
<span class="fc-event-time">11:15</span>

```

You can see in the status (bottom left) that the span tag (with devel\_themer generated classes) is in the link.

This is what the Views Format Settings look like

And the general Views Admin

How might I fix this?

# Answer
There are a lot of little bugs with devel themer. I would just throw a little jquery in one of the js files in the devel\_themer module directory to hide any spans in that tag

```
    $(document).ready(function() {
$('#divnamecontainer a span').remove();
});

```
> 1 votes

---
Tags: views, debugging, javascript
---


# Question
Title: Rendering nodes and other content compatible with all themes
With a group of several people we're creating a system for students.

Now, on that system we're going to have all kinds of modules that have output, e.g., content types with information about events, a page with a hierarchy of people and groups.

What is the Drupal way of rendering this output?

I know that rendering should be done by the themes. But the problem is that our users should be able to pick a theme they want. Creating separate output for each of those themes is just unfeasibly hard.

# Answer
> I know that rendering should be done by the themes.

That is not exactly correct. Theme functions are generally defined from modules, and themes can override them, or implement a theme function that is specific for a purpose.

If you are creating the output for a page, the code for generating it should be in a module. That is because it's a module that can implement hook\_menu(), which is the hook that defines the menu callback used for pages.
That is what is done from Drupal core code with node\_view(), which is the page callback for node/%node, and node/%node/view. The page callback is defined from the Node module, not from a theme; themes can eventually alter the output of `node_view()` through the node.tpl.php template file used from `node_view()` to render the node page.

As for outputting the result, there are two methods:

* Returning a string containing the HTML output
* Returning an array with a specific structure (it is called render array) that can be used from drupal\_render()

As example of a page callback that returns a string, see aggregator\_view(); as example of page callback that returns a render array, see node\_view().
> 1 votes

# Answer
Lots of EDUs use drupal (including mine). For instance Harvard created Open Scholar to power alot of its sites.

**The best way to render content in D7 is render arrays from your modules.**

Pick a sub-set of drupal modules to support. Create a base theme that implements decent CSS selectors and coloring across all these modules (and their output), allow users to create sub themes -- or colorize your base theme.

Thats about as flexible as you can get.
> 0 votes

# Answer
I'd also recommend using Skinr. It allows you to preset classes for certain objects/entities. For example, there's a block being placed on a page, and you make a class for blue, red, and green. The user can then say, "Let this be green!" and there you have it.

It might be something worth looking into.
> 0 votes

---
Tags: nodes, theming
---


# Question
Title: How many core Drupal 7 functions are there?
How many functions are in Drupal 7 or how would I find out?

Update: I am thinking of memorizing all of them and think it would be good to know before hand what kind of goal I need to shoot for.

# Answer
There are 4520 PHP functions listed in Drupal 7 core.

Source: http://api.drupal.org/api/drupal/functions/7

50 items per page, 90 full pages + 1 page of 20 = 4520.
> 5 votes

---
Tags: 7
---


# Question
Title: Why isn't there a pager and it doesn't show two records per page?
```
$query = db_select('node', 'n');
$query->condition('n.type', 'article', '=')
  ->fields('n', array('nid', 'title', 'uid'))
  ->extend('PagerDefault')
  ->limit(2);
$result = $query->execute();

while($record = $result->fetchObject()) {
  echo $record ->title."<br/>";
}

$output .= theme('pager', array('tags' => array()));

```

I put the above code in a page template file. Why isn't there a pager and it doesn't show two records per page?

# Answer
The code is wrong: Once you extend the query object, you need to save it, or it will get lost. The correct code is the following one.

```
$query = db_select('node', 'n');
$query = $query->condition('n.type', 'article', '=')
  ->fields('n', array('nid', 'title', 'uid'))
  ->extend('PagerDefault')
  ->limit(2);

$result = $query->execute();

foreach ($result as $node) {
  echo $node->title . "<br/>";
}

```

In my case, the result is the following one.

> Appellatio Fere Huic Metuo
> Ludus Vereor

See the note shown on Extenders:

> Note that `$query` is not altered in place. The new object is returned from `extend()`, and if it is not saved to a variable it will be lost.
> 1 votes

---
Tags: 7
---


# Question
Title: How do I add a pager for the following code?
On the `page--product.tpl.php` I use `node_load()` to get all the nodes of a content type. I want to shows 15 post titles per page. How do I add a pager to the page?

I am using the following code.

```
$terms = taxonomy_get_children(arg(2));
foreach ($terms as $term) {
  $whole = taxonomy_select_nodes($term->tid, TRUE, 1, array('t.created' => 'DESC'));
  foreach ($whole as $nid) {
    $node_this = node_load($nid);
    echo '<h1 class="pdtitle"><a href="#">'.$node_this->title.'</a></h1>';
  }
}

```

# Answer
Execute the following code, and you should get a pager.

```
function mymodule_get_children($tid) {
  $query = db_select('taxonomy_term_data', 't');
  $query->join('taxonomy_term_hierarchy', 'h', 'h.tid = t.tid');
  $query->addField('t', 'tid');
  $query->condition('h.parent', $tid);
  $query->addTag('term_access');
  $query->orderBy('t.weight');
  $query->orderBy('t.name');
  $tids = $query->execute()->fetchCol();

  return $tids;
}

function mymodule_select_nodes(array $tids, $pager = TRUE, $limit = FALSE, $order = array('t.sticky' => 'DESC', 't.created' => 'DESC')) {
  if (!variable_get('taxonomy_maintain_index_table', TRUE)) {
    return array();
  }
  $query = db_select('taxonomy_index', 't');
  $query->addTag('node_access');
  $query->condition('tid', $tids);
  if ($pager) {
    $count_query = clone $query;
    $count_query->addExpression('COUNT(t.nid)');

    $query = $query->extend('PagerDefault');
    if ($limit !== FALSE) {
      $query = $query->limit($limit);
    }
    $query->setCountQuery($count_query);
  }
  else {
    if ($limit !== FALSE) {
      $query->range(0, $limit);
    }
  }
  $query->addField('t', 'nid');
  $query->addField('t', 'tid');
  foreach ($order as $field => $direction) {
    $query->orderBy($field, $direction);
    // ORDER BY fields need to be loaded too, assume they are in the form
    // table_alias.name
    list($table_alias, $name) = explode('.', $field);
    $query->addField($table_alias, $name);
  }
  return $query->execute()->fetchCol();
}

$tids = mymodule_get_children(arg(2));

if (!empty($tids)) {
  $nids = mymodule_select_nodes($tids, TRUE, 1, array('t.created' => 'DESC'));

  if (!empty($nids)) {
    $nodes = node_load_multiple($nids);
    foreach ($nodes as $node) {
      echo '<h1 class="pdtitle"><a href="#">'.$node->title.'</a></h1>';
    }
  }

  echo theme('pager');
}

```

In my test site, replacing `arg(2)` with an existing taxonomy term ID, I get the following output.

```
<h1 class="pdtitle"><a href="#">Appellatio Fere Huic Metuo</a></h1><h2 class="element-invisible">Pages</h2><div class="item-list"><ul class="pager"><li class="pager-current first">1</li>
<li class="pager-item"><a title="Go to page 2" href="/dr72/devel/php?page=1">2</a></li>
<li class="pager-item"><a title="Go to page 3" href="/dr72/devel/php?page=2">3</a></li>
<li class="pager-item"><a title="Go to page 4" href="/dr72/devel/php?page=3">4</a></li>
<li class="pager-item"><a title="Go to page 5" href="/dr72/devel/php?page=4">5</a></li>
<li class="pager-item"><a title="Go to page 6" href="/dr72/devel/php?page=5">6</a></li>
<li class="pager-item"><a title="Go to page 7" href="/dr72/devel/php?page=6">7</a></li>
<li class="pager-item"><a title="Go to page 8" href="/dr72/devel/php?page=7">8</a></li>
<li class="pager-item"><a title="Go to page 9" href="/dr72/devel/php?page=8">9</a></li>
<li class="pager-ellipsis">…</li>
<li class="pager-next"><a title="Go to next page" href="/dr72/devel/php?page=1">next ›</a></li>
<li class="pager-last last"><a title="Go to last page" href="/dr72/devel/php?page=302">last »</a></li>
</ul></div>

```

I used my own functions for the following reasons:

* `taxonomy_get_children()` returns an array of term objects while you are interested only in the taxonomy term IDs. My code gets directly the taxonomy term IDs.
* `taxonomy_select_nodes()` accepts a single taxonomy term ID, while you need the nodes using one or more taxonomy terms. My code returns all the nodes using one or more taxonomy terms matching an array of taxonomy terms.

I also created the page--taxonomy.tpl.php file for the currently enabled theme, and the code works, when I visit the taxonomy page for a taxonomy term with child terms.

In my case, the taxonomy term doesn't have nodes using it, but it has child terms used in nodes.

### Update

The problem is that both the code you want to add in the template file, and the code executed from Drupal are trying to do the same thing, and this causes a conflict between the two. As result, when a taxonomy term has nodes using it, the output is just the one from Drupal.

When there aren't nodes using the taxonomy term, the output is from the custom template file, and from Drupal.

Both the screenshots has been taken using your theme as default theme.

To avoid this, the code needs to be changed to the following one.

```
function mymodule_get_children($tid) {
  $query = db_select('taxonomy_term_data', 't');
  $query->join('taxonomy_term_hierarchy', 'h', 'h.tid = t.tid');
  $query->addField('t', 'tid');
  $query->condition('h.parent', $tid);
  $query->addTag('term_access');
  $query->orderBy('t.weight');
  $query->orderBy('t.name');
  $tids = $query->execute()->fetchCol();

  return $tids;
}

function mymodule_select_nodes(array $tids, $pager = TRUE, $limit = FALSE, $order = array('t.sticky' => 'DESC', 't.created' => 'DESC')) {
  if (!variable_get('taxonomy_maintain_index_table', TRUE)) {
    return array();
  }
  $query = db_select('taxonomy_index', 't');
  $query->addTag('node_access');
  $query->condition('tid', $tids);
  if ($pager) {
    $count_query = clone $query;
    $count_query->addExpression('COUNT(t.nid)');

    $query = $query->extend('PagerDefault');
    $query->element(10);
    if ($limit !== FALSE) {
      $query = $query->limit($limit);
    }
    $query->setCountQuery($count_query);
  }
  else {
    if ($limit !== FALSE) {
      $query->range(0, $limit);
    }
  }
  $query->addField('t', 'nid');
  $query->addField('t', 'tid');
  foreach ($order as $field => $direction) {
    $query->orderBy($field, $direction);
    // ORDER BY fields need to be loaded too, assume they are in the form
    // table_alias.name
    list($table_alias, $name) = explode('.', $field);
    $query->addField($table_alias, $name);
  }
  return $query->execute()->fetchCol();
}

$tids = mymodule_get_children(arg(2));

if (!empty($tids)) {
  $nids = mymodule_select_nodes($tids, TRUE, 1, array('t.created' => 'DESC'));

  if (!empty($nids)) {
    $nodes = node_load_multiple($nids);
    foreach ($nodes as $node) {
      echo '<h1 class="pdtitle"><a href="#">'.$node->title.'</a></h1>';
    }
  }

  echo theme('pager', array('element' => 10));
}

```

The difference is that now the code is setting the "element" property for the pager to 10. It should the conflict between the pagers, but it changes the value for the GET parameter "page" used from Drupal to identify which page of the pager should be shown, which become similar to "page=0,0,0,0,0,0,0,0,0,1"; when shown in the URL, it is probable the commas are encoded.

As I commented before, this is not the code I would put in a template file. If you want to change the output of a page, you change its page callback, which means implementing code similar to the following one. (The following is just partial code.)

```
function mymodule_menu(&$items) {
  if (isset($items['taxonomy/term/%taxonomy_term'])) {
    $items['taxonomy/term/%taxonomy_term']['page callback'] = 'mymodule_term_page';
  }
}

```

Even better, it would be using the Views module, and using a view for the taxonomy term page. In this way, it would be possible to alter the output without to write code, and without altering any template file.

In both the cases, Drupal would not be adding a pager while another pager is being added to the same page from a module.

As side note, you are putting in template files things that should be in a module, or that can be easily obtained changing settings for already enabled modules.
> 1 votes

# Answer
I think you are trying to do a custom pager, not based on db query something like this, but it is D6 code.
For D7, check Extenders and what the Database Abstraction Layer page describes is

> Most Drupal database SELECT queries are performed by a call to db\_query() or db\_query\_range(). Module authors should also consider using the PagerDefault Extender for queries that return results that need to be presented on multiple pages

You may also need to check theme\_pager which displays the pager result. When calling `theme('pager')` outside a pager query, it's necessary to initialize the pager first with a call to pager\_default\_initialize.
> 1 votes

---
Tags: 7
---


# Question
Title: Calling Module function from jQuery and Ajax
With every drupal site I make, I usually create a custom module that I use to hold different php functions and other things custom to the site I am working on. It usually only consists of a module\_name.module and module\_name.info. Additionally, I always have .js file in the theme to do any javascripts I might need. Pretty standard right? But I have now run into a situation where I need the two to talk to one another.

I know you can call a .php file and pass it data using .ajax in jquery. How would I envoke a function written in my custom module from the js file in my theme?

# Answer
> 1 votes
Hopefully this will help -- got this code from a Lullabot module development training.

It all revolves around a hook\_menu callback. The value in 'page callback' is the function that will be called, in this case it is: "**menu\_magic\_page**"

So Drupal looks for the menu\_magic\_page() function.

Your jQuery / AJAX call would then reference the value what's in $items\['X'\] where X is "**magic**" here. So hitting http://example.com/magic would run the module function "**menu\_magic\_page**"

FWIW: the type/MENU\_CALLBACK ensures it doesn't get added to menu's etc. It just ensures Drupal is ready to process it.

Hope this helps.

```
/**
 * Implements hook_menu().
 */
function menu_magic_menu() {
  $items = array();

  /**
   * This is a simple callback.
   *
   * This will create a path at http://example.com/magic. When visited, that
   * URL will trigger the "menu_magic_page" function.
   */

  $items['magic'] = array(
    'title' => 'Menu Magic!',
    'page callback' => 'menu_magic_page',
    'type' => MENU_CALLBACK,
  );

/**
 * Page callback for 'magic'. This is the function that will get called
 * everytime a user visits http://example.com/magic.
 */
function menu_magic_page() {
  global $user;
  return t('Hello, @username!', array('@username' => $user->name));
}

```

---
Tags: 7, ajax, javascript
---


# Question
Title: Why do I get PDOException SQLSTATE[42S22] Column not found 1054 Unknown column 'tn.tid' in 'on clause'"?
```
$rtid = arg(2);

$query = "SELECT node.nid AS nid FROM node
  WHERE (node.nid IN (
    SELECT tn.nid AS nid
    FROM taxonomy_index AS tn
    LEFT OUTER JOIN taxonomy_term_hierarchy AS th ON th.tid = tn.tid
    LEFT OUTER JOIN taxonomy_term_hierarchy AS th1 ON th.parent = th1.tid
    LEFT OUTER JOIN taxonomy_term_hierarchy AS th2 ON th1.parent = th2.tid
    WHERE (tn.tid = :rtid) OR (th1.tid = :rtid) OR (th2.tid = :rtid)
  ))
  AND (node.status = '1') AND (node.type IN ('product'))
  ORDER BY node_created DESC
  LIMIT 1 OFFSET 0";

$result = db_query($query, array(':rtid' => $rtid));

```

After I tried some times with the help of other users' answers, I got lost. This is the code I tried, but it gives me an error ("PDOException SQLSTATE\[42S22\] Column not found 1054 Unknown column 'tn.tid' in 'on clause'").

```
$query = db_select('node', 'n')
  ->condition('n.type', 'product')
  ->condition(
    db_or()
      ->condition('tn.tid',$rtid )
      ->condition('th1.tid',$rtid)
      ->condition('th2.tid',$rtid)
  )
  ->fields('n', array('nid'))
  ->extend('PagerDefault')
  ->limit(1);

$query->join('taxonomy_term_hierarchy', 'th', 'th.tid = tn.tid');
$query->join('taxonomy_term_hierarchy', 'th1', 'th.parent = th1.tid');
$query->join('taxonomy_term_hierarchy', 'th2', 'th1.parent = th2.tid');

$result = $query->execute();

```

# Answer
> 1 votes
The error you get is caused by the fact you don't use tn as alias of any database table.

The code I would write is the following one.

```
$tid = arg(2);
$query = db_select('node', 'n');

$tn = $query->join('taxonomy_index', 'ti', '%alias.nid = n.nid');
$th = $query->join('taxonomy_term_hierarchy', 'th', "%alias.tid = $tn.tid");
$th1 = $query->join('taxonomy_term_hierarchy', 'th1', "%alias.tid = $th.parent");
$th2 = $query->join('taxonomy_term_hierarchy', 'th2', "%alias.tid = $th1.parent");

$query->condition('n.type', 'product')
  ->condition(
    db_or()
      ->condition("$tn.tid", $tid)
      ->condition("$th1.parent", $tid)
      ->condition("$th2.parent", $tid)
  )
  ->fields('n', array('nid'))
  ->extend('PagerDefault')
  ->limit(1);

```

`$query->join()` is really doing an INNER join; if you need to make a LEFT OUTER join, then the code is the following.

```
$tid = arg(2);
$query = db_select('node', 'n');

$tn = $query->join('taxonomy_index', 'tn', '%alias.nid = n.nid');
$th = $query->addJoin('LEFT OUTER', 'taxonomy_term_hierarchy', 'th', "%alias.tid = $tn.tid");
$th1 = $query->addJoin('LEFT OUTER', 'taxonomy_term_hierarchy', 'th1', "%alias.tid = $th.parent");
$th2 = $query->addJoin('LEFT OUTER', 'taxonomy_term_hierarchy', 'th2', "%alias.tid = $th1.parent");

$query->condition('n.type', 'product')
  ->condition(
    db_or()
      ->condition("$tn.tid", $tid)
      ->condition("$th1.parent", $tid)
      ->condition("$th2.parent", $tid)
  )
  ->fields('n', array('nid'))
  ->extend('PagerDefault')
  ->limit(1);

```

As side notes:

* `$query->join()`, and `$query->addJoin()` returns the alias they used
* In the conditions passed to `$query->join()`, and `$query->addJoin()` %alias is replaced with the table alias the method is using

SelectQuery::addJoin() avoids conflicts between aliases using the following code.

```
  $alias_candidate = $alias;
  $count = 2;
  while (!empty($this->tables[$alias_candidate])) {
    $alias_candidate = $alias . '_' . $count++;
  }
  $alias = $alias_candidate;

  if (is_string($condition)) {
    $condition = str_replace('%alias', $alias, $condition);
  }

```

Writing code similar to the one I used, you are sure not to cause any conflict between aliases, and it is useful in the case the code is changed successively, or part of the query is populated from a function.
In this case, the join part could have written as follows, and it could still work correctly.

```
$tn = $query->join('taxonomy_index', 'tn', '%alias.nid = n.nid');
$th = $query->join('taxonomy_term_hierarchy', 'th', "%alias.tid = $tn.tid");
$th1 = $query->join('taxonomy_term_hierarchy', 'th', "%alias.tid = $th.parent");
$th2 = $query->join('taxonomy_term_hierarchy', 'th', "%alias.tid = $th1.parent");

```

---
Tags: 7
---


# Question
Title: Why doesn't the pager appear in page--taxonomy.tpl.php?
```
$query = db_select('node', 'n');
$query = $query->condition('n.type', 'article', '=')
  ->fields('n', array('nid', 'title', 'uid'))
  ->extend('PagerDefault')
  ->limit(1);

$result = $query->execute();
while ($record = $result->fetchObject()) {
  echo $record ->title."<br/>";
}

echo theme('pager');

```

If I put the code in page--node--3.tpl.php there is a pager under the title. When I put the same code in page--taxonomy.tpl.php the title is output, but there is no pager. Why?

If there is a term ID, the pager will disappear.

template.php

```
function mythemename_preprocess_page(&$vars)  {
 if (isset($vars['node']->type)) {
$nodetype = $vars['node']->type;
$vars['theme_hook_suggestions'][] ='page__' . $nodetype;
}

}

```

# Answer
> 0 votes
I tried with the Bartik theme, and it works.

The steps I followed as the following ones:

* I copied the page.tpl.php file the Bartik theme has in its templates directory in the page--taxonomy.tpl.php file
* Right before `<?php print render($page['content']); ?>`, I copied the following code.

```
<?php
  $query = db_select('node', 'n');
  $query = $query->condition('n.type', 'article', '=')
    ->fields('n', array('nid', 'title', 'uid'))
    ->extend('PagerDefault')
    ->limit(1);

  $result = $query->execute();
  foreach ($result as $node_obj) {
    echo $node_obj->title . "<br/>";
  }

  echo theme('pager');
?>

```
* I selected another theme instead of the Bartik theme, disabled the Bartik theme, and then selected the Bartik theme as default one. (This step is probably not necessary, but I did it to be sure Drupal would notice I added a new template file.)
* I visited http://tero.local/dr72/taxonomy/term/2.

If it doesn't work for you, I suggest trying with another theme, possibly one that comes with Drupal, for example the Bartik theme. Be sure you are adding the template file to the theme Drupal is using. If the theme selected for the current user is another one, the template file is not being used, and that would explain why you are not getting any output.

This is what I suspect, as the code doesn't depend from `arg(2)`. You just need to visit a page whose path starts with taxonomy, for example http://example.com/taxonomy/term/2, or http://example.com/taxonomy/term. (Replace example.com with the domain you should use for your site.)

### Update

It works, but using the following code.

```
<?php
  $query = db_select('node', 'n');
  $query = $query->condition('n.type', 'article', '=')
    ->fields('n', array('nid', 'title', 'uid'))
    ->extend('PagerDefault')
    ->element(10)
    ->limit(1);

  $result = $query->execute();
  foreach ($result as $node_obj) {
    echo $node_obj->title . "<br/>";
  }

  echo theme('pager', array('element' => 10));
?>

```

Apparently, there is a conflict between the pager added from Drupal, and the pager added from my code. This is the reason why such code should not be added to a template file. Rather than using this method, it is better to override the taxonomy term page with other methods, such as the Views module, or implementing `hook_menu_alter()` in a custom module.

Using the Bartik module this is the output I get:

* When there aren't nodes using that taxonomy term
* When there are nodes using that taxonomy term

Any different result could be caused from the code used for the specific theme used on the site. Understanding what exactly causes the different behavior seems a little outside the purpose of this site, as it is too localized to be helpful for future readers, considering that similar code should not written in a template file.

---
Tags: 7
---


# Question
Title: Horrible frontend performance on large CCK forms = poor UX. What are my options?
I have a pretty large node form for one of my content types. Let's say it has about 100 fields. A lot of these fields are text values with unlimited values, so the user uses an AJAX button to 'Add another item' to each of these. Visually, this form isn't all that intimidating, because I've used Field Groups to keep things reasonable.

**Problem:** Clicking 'Add another item' is freaking slow. Like really slow.

I figured it was server performance, but then I checked it out in Firebug - the request isn't actually taking that long, but WOW - client side CPU usage (in Chrome, Firefox and any other browser I've tried) hits 100% and stays there for up to 11-12 seconds, and then the AJAX request completes.

That's insane.

So at this point I'm not sure what my options are. Can I break the form apart somehow? Workflow-ng style? A lot of people mention Field Groups as a way to organize a ton of fields, but that doesn't help performance, obviously.

Any help appreciated.

# Answer
I have exactly this problem and I can confirm answer #1 - using a multi-step form improved performance, although it was still slow.

The problem is that when the Ajax fires, the entire form is rebuilt in the background. This appears to make huge demands on the server CPU if the form is large.

A multi-step form is a good way of improving things but unfortunately will not always be appropriate - in my case, the client rejected it because they felt it was too annoying to have to progress through the form in a step-by-step linear way. They wanted to be able to jump from tab to tab without saving in between.

Other than fixing Drupal core so that rebuilding the form does not require 20 seconds of max CPU, the only solution I can think of is to try the site out on a high-CPU hosting package, e.g. on Amazon AWS. This will be my next step.

Without knowing much about Drupal core and Ajax, I would call this a bug of sorts. I have heard that the performance of Ajax is being improved in Drupal 8 so I seriously doubt much effort will go into resolving this in D7.

If I had known all this at the start of my project I might have tried solutions such as combining several node forms on one tabbed panel - to break up the server load in more creative ways.
> 2 votes

# Answer
You should probably use a multi-step form. This might be *almost* easily performed using the CTools modules suite.
> 1 votes

---
Tags: 7, entities, performance
---


# Question
Title: Change Product price based on discount set by site owners for different domain - Drupal Commerce
I am working on a website that uses the following modules to create products.

Domain Module to create different domains for different store owners. Drupal Commerce to create products and ecommerce facility.

The idea is each store admin will have a different domain in the website so that they can setup there stores. Also they are able to create the products for their own. The product types have a field called "Commission", which stores a value in it. It is used to pay back some commission to the store owners if that product is purchased from the site owner's store.

Each site owner has a admin page where a custom module sets a variable called "Discount" which will denote the percentage of discount to apply in each product globally only to that domain.

As an example, suppose a domain store has a product with $100 and that product has a Commission 25% the upon selling that product the domain's site owner will get $25. But if that site owner sets the global Discount variable as 50% then the buying user will have a discount on $100 product of 12.5% as $87.50 and the site owner will get commission as 12.5% as $12.50.

Is there any way or HOOK that I could use to alter the price once it goes to the Checkout page?

# Answer
The easiest thing is to hook into rules, as there is a rules event, for when the price for a product is being calculated: `commerce_product_calculate_sell_price`. This event is designed to hook into, in order to change price for discounts and the like.

You can create your own custom action to provide the discount, or try to use the Rules interface to setup the logic there.
> 2 votes

---
Tags: commerce, domain-access
---


# Question
Title: Programmatically deleting a filefield content and the associated file?
If I do the usual

```
unset($node->myfilefield["und"][0]);

```

Would that take care of the actual deletion of the file as well on node\_save?

# Answer
No, it doesn't. You should use `file_delete()`. The function will remove the attached file from the database and from the disk.

```
// Load the node.
$node = node_load('1');
// Get the language for the file field.
$lang = field_language('node', $node, 'myfilefield');
// load the file
$file = file_load($node->myfilefield[$lang][0]['fid']);
// unset the field for the node
unset($node->myfilefield[$lang][0]);
// delete file from disk and from database
file_delete($file);
// Save the node.
node_save($node);

```

The `file_delete()` also takes a second argument `$force` that if set to `TRUE` will remove the file even if it's reported as in use by the `file_usage` table.
> 7 votes

# Answer
not necessarily call file\_delete(), enough:

```
unset($node->myfilefield["und"][0]);
node_save($node);

```
> 0 votes

---
Tags: 7, files
---


# Question
Title: z-index Drupal 7 Skeleton Boilerplate discriminating roles?
I'm building a website using Drupal 7 for the first time. I have always built them on Drupal 6 using the basic theme to build my own custom themes from. This time I decided to change, because I thought it was time to move onto Drupal 7 and I wanted responsive design for this project.

I have a custom front---page template, and on that front page I have views slideshow (cycle) and wanted to place text on it. So i made a block with such text, and gave it a z-index 999 and an absolute position, when the slider has a z-index -999. Everything looks just as I want it and expect it to, until.... I log out! Is it possible that the css is discriminating roles?

How can it possibly be that logged in as admin I see the slider on the bottom and the block on top as expected, and as an anonymous user the text block is hidden underneath the slider? (And I know it is because when I resize, I can partially see it, as it moves down.... ) I'm lost.

Edit for more info: this is happening in IE9, Chrome, Safari mac, Safari Win, and Firefox is displacing the Slider onto the right....GRRRR. HELP! Thank you in advance for your help.

# Answer
I was too quick to post the question and I apologize, since the answer is all over the internet, and for those going through the same issue:

**YOU MUST add position relative or absolute to all items** involved in the z-indexing. Ot the z-index won't work.

Also why was Firefox not rendering things right? I had added a skeleton class to the search box template, but had not added a clear right after.

As to why it was rendering things right when i was logged in as an admin, but not when I was anonymous, remains a mystery.

Hope this is useful for those having identical issues.
> 0 votes

---
Tags: users, theming
---