# Question
Title: Rules + Button Field: getting entity object to a custom action
I am using Rules 7.x-2.2 with the latest version of Button Field (http://drupal.org/project/button\_field), Session API (http://drupal.org/project/session\_api) and a custom module to store some entity values in a user's session when they click a button.

To clarify, I have an entity type (Commerce product) with an HTML instance of the button field that is supposed to trigger a custom defined rules action, where I want to extract some values from the entity object that the button is associated with.

This is how my Rules action info looks currently in my custom module:

```
function commerce_custom_box_rules_action_info() {
    return array(
        'commerce_custom_box_add_to_box' => array(
            'group' => t('Commerce Custom Box'),
            'label' => t("Add the product to the user's box"),
            'parameter' => array(
                'entity' => array(
                    'label' => t('Product entity'),
                    'description' => t('The entity the clicked button is attached to.'),
                    'type' => 'entity',
                ),
            ),
        ),
    );
}

```

And here is how my rule looks:

The problem is, in `commerce_custom_box_add_to_box()` (the function fired by my custom action), I have tried using `dpm()` on all of its arguments and none of them contain any entity properties, field values, or anything else that could even be remotely useful. All I get are empty "EntityDrupalWrapper" objects and similar. However, if I replace the action in the rule with "Execute PHP Code", there is an $entity object available there and dpm() reveals that it is in fact populated with all the usual properties.

Naturally I am trying to figure out why that object is there but isn't being received by my custom action. Perhaps I'm thinking about it in the wrong way?

A fresh pair of eyes on this would be hugely appreciated! Happy to provide more info if needed.

# Answer
It turns out this was caused by the parameter type I used. I set it to "entity", whereas it should be the machine name of the entity type. Changing it to "commerce\_product" has fixed the problem.
> 1 votes

---
Tags: 7, commerce, rules, actions
---


# Question
Title: Drupal 7 views - sort results after they have been retrieved from database just before they are rendered
Drupal 7 views - sort results after they have been retrieved from database just before they are rendered. Here what type of hook need to use.Is the below hook usefull? hook\_views\_data\_alter()

Thanks, Ramesh Babu G.

# Answer
You can implement hook\_views\_pre\_render(&$view) within a custom module and manipulate the result array available in $view-\>result:

```
/**
 * Implementation of hook_views_pre_render()
 *
 * @param view $view
 */
function YourModuleName_views_pre_render(&$view) {
  // Check if this is the view and display you want to manipulate
  // NOTE: Adjust/Remove the display check, if you want to manipulate some/all displays of the view
  if ('YourViewName' == $view->name && 'YourDisplayName' == $view->current_display) {
    // EXAMPLE: Just reverse result order
    // TODO: Replace with your desired (re)ordering logic
    $view->result = array_reverse($view->result);
  }
}

```
> 1 votes

---
Tags: database, views
---


title: User Permissions

text:
# Question
Title: User Permissions
I have created a user role ,and granted it all the necessary permissions.

However, it looks like I've missed something:

Users who are assigned this role cannot update the content. They can see the content in the content list, click "edit" and see the node edit page, but on the "body" field with the content itself, there's an error message stating:

> **This field has been disabled because you do not have sufficient permissions to edit it.**

.

# Answer
You need to also give the 'content manager' role access to use one or more of the filters (Full HTML, Filtered HTML, etc) otherwise they won't be able to edit the body

You can do that on the normal permissions page, just search for 'Filter' and you should find them
> 7 votes

---
Tags: users
---


title: Migrate text field with multiple values

text:
# Question
Title: Migrate text field with multiple values
I've got a simple Text field which allows 2 values, let's call it `field_text`. My source database has two columns, let's say `text1` and `text2`.

I want to set my migrate field mapping so that `text1` is used as the first value for `field_text` and use `text2` as the second value for `field_text`.

In other words, something like this:

```
$this->addFieldMapping('field_text[0]', 'text1');
$this->addFieldMapping('field_text[1]', 'text2');

```

# Answer
You should implement prepareRow() method in your migration class. Inside prepareRow() you can read both source fields and add them to an array. I will provide an example:

```
public function prepareRow($row) {
  $row->text1 = array($row->text1, $row->text2);
}

```

Now your source field "text1" will contain both values and it can be mapped to "field\_text". "text2" has to be set to DNM (do not map).
> 10 votes

---
Tags: 7, migrations, entities
---


# Question
Title: Taxonomy View - show only terms with children
I have a view of terms where I show in a grid terms form the highest level (those with parent = 0). I have to limit this view to only show those terms that contain at least one child term. I can't figure out how to do this. Anyone? Thanks!

# Answer
I would do quite as Arthur did, but I don't think double relationship is necessary :

1. Set a relationship "parent term"
2. Make it mandatory
3. Display "term" **with** the relationship

You then will have only parent terms with children displaying.

Of course, you'll then have to aggregate or group to avoid duplications of parents with multiple children.
> 2 votes

# Answer
I would say trying to do it via Views UI would be bending views too much. How about putting together the query yourself and then using views for rendering. As described in this Drupal post - http://drupal.org/node/409808

And here is another article that talks about "programming" views - http://www.metaltoad.com/blog/views-3-makes-programmers-happy

Does that help?
> 0 votes

# Answer
How about reversing the approach: rather than selecting parents with children, select children but display their parents. You'd need to establish a double relation for that. First, you need to look for the parent and make it required, and then - from the parent - establish a parent-of-parent relation - and that ancestor should be null (if what you meant was the topmost level).
> 0 votes

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


title: Global Variable

text:
# Question
Title: Global Variable
I have the following problem: I want to create a product catalogue. In the catalogue there are different types (Content Types) of products: eg chairs, tables, couches (i approached that with content types and taxonomy terms). How can I implement a "switch" button, that switches between private customers and business clients. I think there should be a checkboxfield in the content type, so i can define, that a certain chair is visible for business or for private or for all clients. How can I filter this information? How can I display these items in a menu? Thanks for the Help!

# Answer
You have so many ways to do this :) I guess the smartest would be to create a taxonomy vocabulary with only two terms.

Or you could have a simple "text field / multiple choices" field.

But taxonomy would be smarter I guess.
> 0 votes

---
Tags: taxonomy-terms, routes
---


# Question
Title: How to use addField function when the field name is SQL keyword
I have a field with name 'order' in the database. How to select it, using addField?

```
$query->addField('sco_groups', 'order');

```

Gives an error.

# Answer
I fixed it, using this code:

```
$query->addField('sco_groups', 'order', 'field_order');

```
> 2 votes

---
Tags: 7, database
---


title: How fast does Drupal send email?

text:
# Question
Title: How fast does Drupal send email?
My SMTP server has sending limit up to 5 messages per second. On Drupal 6 site I have up to 500 users in organic groups to whom I would like to send newsletter.

What sending limit should I set for successful broadcast? Does Drupal send messages momentarily or during longer period?

**UPDATE**

I use Messages & Notifications modules which allow me to limit

* number of messages
* sending time in seconds
* sending time in % of cron time

The only way to solve my problem I've found up to now is limiting the number of messages to 5 and setting cron to run every 15 minutes. But it is very sad to wait whole day to send about 500 messages.

# Answer
> 0 votes
If you start tracing from `drupal_mail()`, you will end up in the MailSystem. The `DefaultMailSystem::mail()` method sends out mail, unless another module has done otherwise. This hands off the email to the PHP `mail()` function, which does something system dependent.

As far as I been able to tell when I have debugged email problems, Drupal doesn't do any throttling. Typically, PHP doesn't throttle either. After that, it really varies and totally depends on the php.ini settings and other server setup.

# Answer
> 0 votes
I've had problems with mails not reaching a custom Google apps email address from the default mail function. Therefor I use SMTP module to handle my emails. It connects to every mail account(supports SMTP), and uses that to send a mail.

It works with Google Apps, and mail is sent instantly.

---
Tags: 6, emails
---


title: Drupal Services Bad request

text:
# Question
Title: Drupal Services Bad request
I have a drupal7 Site, in which I activated the services module to expose a SOAP service. The problem is that I set up everything, the endpoints, the handling of the request, load the WSDL and set the class to get th efunctions, but I always get an error

```
function tigoapi_server() {

require_once 'ServicePort.php';
global $HTTP_RAW_POST_DATA;
$server = new SoapServer(drupal_get_path('module', 'tigoapi') . '/wsdl/TigoAPIService_1.wsdl');
ini_set("soap.wsdl_cache_enabled", "0"); // disabling WSDL after the server is initiated
$server->setClass('ServicePort');

error_log(print_r($server->getFunctions(),true),3,"/var/www/sites/tigo/sites/all/modules/services/tigoapi/tigoapi.log");
$server->handle($HTTP_RAW_POST_DATA);

```

I always get:

```
curl http://server/tigoapi?wsdl
<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"><SOAP-ENV:Body><SOAP-ENV:Fault><faultcode>SOAP-ENV:Client</faultcode><faultstring>Bad     Request</faultstring></SOAP-ENV:Fault></SOAP-ENV:Body></SOAP-ENV:Envelope

```

Now, if I try it , same server, same WSDL, same ServicePort class, just not going throug the Drupal router it works:

```
    require_once 'ServicePort.php';
global $HTTP_RAW_POST_DATA;
//$server = new SoapServer(drupal_get_path('module', 'tigoapi') . '\wsdl\TigoAPIService_1.wsdl',array('encoding'=>'UTF-8'));
$server = new SoapServer('wsdl/TigoAPIService_1.wsdl');
ini_set("soap.wsdl_cache_enabled", "0"); // disabling WSDL after the server is initiated
    $server->setClass('ServicePort');

    error_log(print_r($server->getFunctions(),true),3,"/var/www/sites/tigo/sites/all/modules/services/tigoapi/tigoapi.log");
//$server->handle();
$server->handle($HTTP_RAW_POST_DATA);

```

This works perfectly.

I'm using nginx and php-fpm, it would seem that the difference is in the way the requests gets here as with drupal I have a $\_GET variable called 'q'

any ideas on this?

# Answer
Ok it seems I'm implementing it wrong. The SoapServer::handle() source code shows why:

```
 if (SG(request_info).request_method &&
        strcmp(SG(request_info).request_method, "GET") == 0 &&
        SG(request_info).query_string &&stricmp(SG(request_info).query_string, "wsdl") == 0) {.....

```

the Get parameter must be wsdl, which Drupal rewrites. Also in essence using the SoapServer drupal module you get around this. references to implement this properly:

example More info Soap server module
> 1 votes

---
Tags: services
---


# Question
Title: How can I ensure a user field is hidden by default for the logged in user?
Module X provides a field-definition and attaches it to the user-entity.

Attaching metadata to the user in that way makes for a very convenient way to access it across the site.

However, by default, a logged in user will also be able to both view and edit this data, which is not always desirable.

Is there a way for the same module to ensure that this field is hidden by default?

# Answer
If you don't want to depend from a module implemented by others, you can implement hook\_field\_access() in your own module. It is quite easy to change the access permission for an entity field, knowing its name.

```
function mymodule_field_access($op, $field, $entity_type, $entity, $account) {
  if ($field['field_name'] == 'field_of_interest' && $op == 'edit') {
    return user_access('edit field of interest', $account);
  }
  return TRUE;
}

```

`$op` is `'edit'`, or `view'`; `$entity` contains the object for the entity to which the field is attached; `$entity_type` is the entity type.

With a module that aims the specific fields for which you want to control the access, it is easy to enable the access control: Just enable the module when you need it, and disable it when the access control is not necessary.
> 4 votes

# Answer
1. Depend on field\_permission.
2. Export permissions for the field.
3. Set the permissions to FALSE on hook\_install.
> 0 votes

---
Tags: entities, users
---


title: Remove fieldset from date field

text:
# Question
Title: Remove fieldset from date field
I am trying to remove the `<fieldset>` surrounding a date popup field, but I find that the label is also removed. This is my code:

```
function mymodule_profile_form_alter(&$form, $form_state, $form_id) {

  global $user;
  //print_r($form['field_last_name']);

  $form['field_birthdate']['und'][0]['#theme_wrappers']=$form['field_birthdate']['und'][0]['#theme_wrappers'][0];
}

```

Can anyone help me to solve this problem?

# Answer
> 3 votes
Typically there is a theme function associated with the different sort of output you can give data fields or indeed any fields If you want to change this you do so on the theme level by overriding the default theme function in your themes template.php file.

**Date popup**

```
function YOURTHEME_date_popup($vars) {
  $element = $vars['element'];
  $attributes = !empty($element['#wrapper_attributes']) ? $element['#wrapper_attributes'] : array('class' => array());
  $attributes['class'][] = 'container-inline-date';
  // If there is no description, the floating date elements need some extra padding below them.
  $wrapper_attributes = array('class' => array('date-padding'));
  if (empty($element['date']['#description'])) {
    $wrapper_attributes['class'][] = 'clearfix';
  }
  // Add an wrapper to mimic the way a single value field works, for ease in using #states.
  if (isset($element['#children'])) {
    $element['#children'] = '<div id="' . $element['#id'] . '" ' . drupal_attributes($wrapper_attributes) .'>' . $element['#children'] . '</div>';
  }
  return '<div ' . drupal_attributes($attributes) .'>' . theme('form_element', $element) . '</div>';
}

```

Although it must be said this is being themed as a form\_element so there is no fieldset.

**Date combo** is themed as a fieldset and again can be overriden...

```
function YOURTHEME_date_combo($variables) {
    $element = $variables['element'];
    $field = field_info_field($element['#field_name']);
    $instance = field_info_instance($element['#entity_type'], $element['#field_name'], $element['#bundle']);

    // Group start/end items together in fieldset.
    $fieldset = array(
            '#title' => t($element['#title']) . ' ' . ($element['#delta'] > 0 ? intval($element['#delta'] + 1) : ''),
            '#value' => '',
            '#description' => !empty($element['#fieldset_description']) ? $element['#fieldset_description'] : '',
            '#attributes' => array(),
            '#children' => $element['#children'],
    );

    // Fix required marker.
    if ($element['#required']) {
        $fieldset['#title'] .= " " . theme('form_required_marker');
    }
    return theme('fieldset', array('element' => $fieldset));
}

```

If you replaced 'fieldset' with 'form\_element' this would work.

---
Tags: forms
---


title: View will not group the taxonomy terms

text:
# Question
Title: View will not group the taxonomy terms
I am litterally pulling my hair out and I hope that someone can help! I'm working in Drupal 7 with Commerce Kickstart and all I want is to be able to view the flowers, grouped by their taxonomy term.

For example: Flowers with bloom size of 5.5 inches:
flower teaser flower teaser flower teaser flower teaser

Flowers with bloom size of 4 inches
flower teaser flower teaser flower teaser flower teaser

etc.

Right now in the view I'm using the "grid" format grouping by the Taxonomy term name Bloom size - I have the "use rendered output to group rows" checked, but it will not group my terms and it keeps putting the same heading on down the page above each teaser. You can see it here: 64.34.70.141/~henryl/bloom-size

I have a feeling it's something simple that I'm missing but I've spent DAYS on this one page and combing through other view examples and google searches and I can't figure it out. Does anyone have any ideas?

Thank you!!!!!!

Candace

# Answer
> 1 votes
What do you have the "sort" criteria set to? Also, I find the default Views grid-view to be quite awful. I use the Views Fixed Grid module for any grid views. It will give you better output and greater control in my humble opinion.

---
Tags: views, commerce
---


title: Profile fields export/import

text:
# Question
Title: Profile fields export/import
I have many user profile fields created at admin/config/people/accounts/fields in my drupal 7 local (offline) site. I would like to transfer all fields configuration to my online drupal site.
Is there any way to do this like views export/import feature? I don't want to re-create all fields in my online site.

# Answer
The Features module can export content types, fields, views and allow you to import into another Drupal site.

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

# Answer
One option could be the Bundle Copy module that lets you export and import the whole user entity.

Another option would be the Field Tools module that provides export/import functionalities specific for fields.
> 3 votes

---
Tags: users
---


# Question
Title: Drupal 7 Search results have no theme or format (no HTML)
I have a Drupal 7 installation with about 10 custom types and a custom theme. I have a search form in the site's header displayed with

```
$block = module_invoke('search', 'block_view', 'form');
print render($block);

```

This code is in an include file called by my page.tpl.php, it's not actually inside a block.

If there are no search results, the search page displays (mostly) correctly and it uses the search-results.tpl.php template in my theme.

However, if there ***are*** search results, I get an unformatted page. It's just the search results (with their associated HTML p tags, etc.) with no site HTML. No head tag, no body tag and none of the custom theme's HTML.

By using advanced search, I have identified, specifically, that one of my custom types is causing this issue. The confusing thing is that this type just has a title and a body text. Other, more complicated types are not causing this issue. When I limit it by type, I get the correct output.

How can I get the search results to show up on a regularly themed page?

---

## EDIT

I have also tried:

```
echo drupal_render(drupal_get_form('search_form'));

```

# Answer
> 1 votes
I don't know if this will help anyone; but, just in case, here is the solution to my problem.

One of my content types (the one causing the issue) is only viewable in the public site via ajax. As such, I had this code in my function \*mytheme\_node\_view\_alter(&$build)\*

```
//show only output for popup
if($build['#node']->type=="blue_pop_up"){
    echo $build['#node']->body["und"][0]["safe_value"];
    die();
}

```

This was breaking my search results page when it found content of this type. I simply added this to the code:

```
//show only output for popup
    if($build['#node']->type=="blue_pop_up")
    {
        if($build["body"]["#view_mode"] != "search_result")
        {
            echo $build['#node']->body["und"][0]["safe_value"];
            die();
        }
    }

```

---
Tags: search
---


# Question
Title: Easiest way to expose existing data in secondary database as entities?
Given a "node-like" database table in an "external" or "secondary" database, what's the easiest way to expose them as entities?

Documentation for the entity module makes it seem easy for data stored in the local database, but I'm not sure how that can be translated to another db.

# Answer
Some googling has revealed that the easiest solution is

1. Declare a new entity
2. Create a new Controller class for it that knows how/where to apply data operations.
3. Declare all your metadata as properties as opposed to fields.

I hope I'll be able to expand on this answer once I actually try it out. :)
> 2 votes

---
Tags: entities
---


# Question
Title: Access variables populated in one page function for a different page function? Always null
I have a module that creates a simple page. However in the page I want to link to iframes that I will generate in the module code.

Currently I have two hook\_menu items: one for the simple page (no arguments), one for the iframe pages (with arguments).

However when I show the iframe, I need to get some values from a global variable that is populated from the simple page function but when I reference it in my function for the pages with arguments the variables are always null. I assume this is because drupal re-loads the .module page but skips running the simple page function when it loads the page with arguments, thus it doesn't populate the variables when it loads the iframe.

How could I populate my iframe with the variables from my simple page? Is there an easier way than what I'm doing? Can I do it without global?

Does that make sense?

function `my_custom_page() {}` for:
`drupal/my-custom-page-module`

function `my_iframe($id) {}` for:
`drupal/my-custom-page-iframe/0`

Code for `drupal/my-custom-page-iframe/0` needs to get variables that were generated in function `my_custom_page() {}` when it runs the `my_iframe($id)` for the page callback.

I have defined the variables outside functions as global and included global var\_name in both functions but it still doesn't work.

Also, the iframe should not have any Drupal theme/sidebar content: for this I'm just echo'ing my code and then return: within `my_iframe{$id}`.

What I was thinking was instead of using two functions with page callback, was to just use GET request for my 'iframes' like ?iframe={$id}. Does that sound like a better direction to go?

# Answer
> 0 votes
First off, Drupal is bootstrapped every time a new page is requested. Even if both the pages would be using the same menu callback, the global variables would be reset when passing from a page to the other one.

What you can do is using session variables, passing variables through the URL, or using a cache.
Passing variables through the URL would not use for complex variables, as there is a limit to the URL length accepted from browsers; using a cache would be a solution if the cached data should be available to more than one user, such as to user having the same rule; using session variables is the easier solution when the data to share are only for the currently logged-in users.

As for using the same callback, there is an example given in the hook\_menu() documentation.

```
  function mymodule_menu() {
    $items['abc/def'] = array(
      'page callback' => 'mymodule_abc_view',
    );
    return $items;
  }

  function mymodule_abc_view($ghi = 0, $jkl = '') {
    // ...
  }

```

The menu callback would be used for http://example.com/abc/def, http://example.com/abc/def/222, and http://example.com/abc/def/333/aaaa. In the first case, `$ghi` and `$jkl` would get their default value; in the second case, only `$ikl` would get its default value; in the last case, none of the variables would get their default values.

That is true also for the form builder, with the exception that the first two arguments would be `$form`, and `&$form_state`.

---
Tags: 7, views
---


# Question
Title: Where to add CSS and Javascript directives so they are inserted into the header?
I am attempting to make use of a jQuery script that will enable a "slider" or "slideshow" on my Drupal 7 front page. The instructions for the jQuery plugin (called FlexSlider) say to insert the following items into the header of the page where I want to use the plugin.

```
<!-- Place somewhere in the <head> of your document -->
<link rel="stylesheet" href="flexslider.css" type="text/css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js">`</script>
<script src="jquery.flexslider.js"></script>

```

The problem is I don't know where in my template file I place these directives. I am using a custom front page for Drupal so I have a template file named `page--front.tpl.php`. Do the directives go in there or some other location?

# Answer
The best way to do this is to add the files inside your theme's info file. However you shouldn't need the jquery file, this is included in Drupal core.

```
scripts[] = scripts.js
stylesheets[all][] = style.css

```

Morea bout info files here: http://drupal.org/node/171205
> 2 votes

# Answer
You probably want to use the Drupal Flexslider module, no?

Alternatively you could add the files to your theme and your theme .info file, with

```
scripts[] = 'js/flexslider.js'
stylesheets[all][] = flexslider.css

```

path should be relative to the .info file, so if you say js/flexslider.js the flexslider.js file must be inside the js directory in your theme.

Alternatively with a module and drupal\_add\_js and drupal\_add\_css
> 1 votes

---
Tags: theming, javascript
---


title: Handle Page Content when URL is /abc/1

text:
# Question
Title: Handle Page Content when URL is /abc/1
I want to handle the page content via a drupal module.

If the called URL is abc/\[x\] (for example abc/123, abc/456), then I want to render \[x\] on the page.

which is the best way in drupal to do this *without* views?

Thanks for your answer.

# Answer
If you are asking for the code to write in your own module, I would use the following one.

```
  function mymodule_menu() {
    $items['abc/%'] = array(
      'page callback' => 'mymodule_abc_view',
      'page arguments' => array(1),
    );

    return $items;
  }

  function mymodule_abc_view($value = '') {
    print $value;
  }

```

If the page callback uses `print()`, then the outpage will contain just what the page callback prints; if the page callback returns that value, then the page will contain the value returned from the page callback, and any other thing output from Drupal, such as blocks.

If the number in the URL is an entity ID (for example, a node ID), then the code changes.
Supposing it's a node ID, then the code would be similar to the following one.

```
  function mymodule_menu() {
    $items['abc/%node'] = array(
      'page callback' => 'mymodule_abc_view',
      'page arguments' => array(1),
    );

    return $items;
  }

  function mymodule_abc_view($node = NULL) {
    // Use $node to output something.
  }

```

### References
> 1 votes

# Answer
There are many ways you can accomplish this, here a few ideas;

* You could create custom templates based on the node ID of those pages...Examples here: http://drupal.org/node/1089656
* Also you could make use of the Context module: http://drupal.org/project/context
* You could also, create content in blocks, and set them to only show on the specified paths under the page visibility settings of any given block you create.
> 2 votes

---
Tags: 7
---


# Question
Title: Getting rid of password_confirm labels in module
In a module, the following generates unwanted labels for 'Password' and 'Password confirm':

```
$form['password'] = array(
  '#type' => 'password_confirm',
  '#maxlength' => 20,
  '#size' => 10,
);

```

It produces the following HTML:

```
<div class="form-item form-type-password form-item-password-pass1">
  <label for="edit-password-pass1">Password </label>
  <input class="password-field form-text" type="password" id="edit-password-pass1" name="password[pass1]" size="10" maxlength="128" />
</div>
<div class="form-item form-type-password form-item-password-pass2">
  <label for="edit-password-pass2">Confirm password </label>
  <input class="password-confirm form-text" type="password" id="edit-password-pass2" name="password[pass2]" size="10" maxlength="128" />
</div>

```

The object is to get rid of the text labels and replace them with images. I have tried toggling '#title', '#title\_display' and '#label\_display' but nothing works.

Any ideas?

# Answer
Replacing a label with an image isn't a good idea, mainly for accessibility reasons (an input without a label is a sure way to fail a WAI compliance test).

One simple option would be to set the dimensions and background image of the labels in CSS, and indent the text so it's not visible.

Something like

```
.form-item-password-pass1 label {
  display: block;
  width: 50px;
  height: 50px;
  background: url(/images/50x50.png) left top no-repeat;
  text-indent: -9999em;
}

```

That way you don't actually need to change the markup, and everyone gets the best of both worlds.
> 1 votes

# Answer
I agree with @Clive that it is not a good idea to remove those labels, but there is a way to make them invisible, without to remove them. Drupal 7 has a CSS class for that purpose: *element-invisible*.

The code I would write is similar to the following one.

```
function mymodule_form($form, &$form_state) {
  $form['password'] = array(
    '#type' => 'password_confirm',
    '#maxlength' => 20,
    '#size' => 10,
    '#process' => array('form_process_password_confirm', 'code_testing_process_password', 'user_form_process_password_confirm'),
  );

  return $form;
}

function mymodule_process_password($element) {
  $element['pass1']['#title'] =  '<span class="element-invisible">' . t('Password') . '</span>';
  $element['pass2']['#title'] =  '<span class="element-invisible">' . t('Confirm password') . '</span>';

  return $element;
}

```

The process functions I am using are the same used from the "password\_confirm" form field, except the second one, which is my custom process function I use to make the label invisible.

You could also replace the reference to form\_process\_password\_confirm() if you want to radically change the output for the form fields. The last process function I am using is the one that adds the JavaScript code which checks when the password entered in the two form fields is the same, among other things.
> 2 votes

---
Tags: forms
---


# Question
Title: How can I make a module's configuration exportable by features?
At a high level, what needs to be undertaken to take a module's configuration data and make it exportable by Features?

Whether this is a contrib module that does not yet have Features support or a custom module that I have written, where can I start so that I can get it in code?

# Answer
> 10 votes
Instructions are in the Features API.txt, which provides several examples of how to better integrate your module with Features.

The easiest way seems to be building your module around the CTools Export API. Here's a pretty good article explaining how to do that.

# Answer
> 0 votes
If your module is already taking advantage of the Entity API:

> specify `EntityAPIControllerExportable` as the controller class, set the `exportable` key in `hook_entity_info()` to `TRUE` and include the schema fields necessary (module, status column) by copying the schema as defined in `entity_exportable_schema_fields()` to your `hook_schema()` implementation

See the Community Docs: Make an entity type exportable

---
Tags: features, importing-exporting
---


title: Reward for daily login with rules

text:
# Question
Title: Reward for daily login with rules
I want to reward my users with 1 point for login every 24h.

Event: User has logged in

Condition: ??

Action: Reward points (I have a component)

I don't know how to reward once every 24 hours. how to?

# Answer
Try using User Points modules to manage the points, which has a very good API to integrate with custom modules.

Read this also User Points Contributed modules
> 1 votes

---
Tags: 7, rules, userpoints
---


# Question
Title: Is there an interactive PHP testing tool for Drupal?
I'm in the middle of trying to create some contextphp code and drupal\_set\_message debugging is getting old fast. Is there any tool that would allow me to specify a url "context" (e.g. /node/6) and then have a PHP editor that could dynamically execute the code in the window as if it was running in that context?

# Answer
If you are running locally, you can install Netbeans and Xdebug and set break points, watches and everything.

If you want just a little better then drupal\_set\_message() you can run devel and the output from dpm() will be formatted by Krumo. That's at least helpful.
> 4 votes

---
Tags: 7
---


# Question
Title: How to convert static HTML template to drupal theme
Is there any tools available to convert html template to drupal theme and is there any modules that make drupal 7 theming much easier ?

# Answer
There is no such tool that converts HTML to Drupal theme. But there are services where we can create some kind of Drupal theme with basic `regions` & `templates`.

Some modules you can try

1. Themer *6.x only*
2. Theme developer
3. Skinr

Theming Drupal 6 and 7

Modules for theming

A nice screencast for a beginner Introduction to Theming Basics for Drupal 7
> 1 votes

---
Tags: theming
---


# Question
Title: Customize admin content type page design
i have created template file for my contenttype wallpaper but i don't know how to get form design in that page.

for example

my content type name is wallpaper, so i create template file for `page--node--add--wallpaper.tpl.php` in that page how to get title,body etc ..

(ie)node add to page design.

Thanks for advance

# Answer
> 0 votes
See Drupal 7 Template (Theme Hook) Suggestions

You can do something like `page--node--edit.tpl.php` or `page--node--1.tpl.php`

See the available variables in page.tpl.php

Also you can try `hook_preprocess_page`

```
<?php
function themeName_preprocess_page(&$vars, $hook) {
  if ((arg(0) == 'node') && (arg(1) == 'add' && arg(2) == 'product')) {
    $vars['template_files'][] =  'page-node-add-type';
  }
}
?>

```

---
Tags: nodes, theming, 7
---


title: Get drupal form structure

text:
# Question
Title: Get drupal form structure
I have created content type with CCK in which there are fields like taxonomy, filefield, textfield etc. Now i want form structure of this content type.

# Answer
Try `hook_form_alter`

```
function hook_form_alter(&$form, &$form_state, $form_id) {
 // If you can find the $form_id you can print the exact form.
 print_r($form);
}

```
> 0 votes

---
Tags: forms
---


# Question
Title: How can I create page.tpl for user’s profile page?
Searching in Google I found user-profile.tpl.php , but in fact this is the node of profile page while I want to create page.tpl.php foe the profile page. Also page-user.tpl.php includes login page, register page and all the pages belong to a user which I do not consider, I need to create page.tpl for profile page

# Answer
> 4 votes
the best way to handle this that i've come up with is a combination of 4 files:

* `page-user.tpl.php` for the far-back profile edit as igor said
* `user-profile.tpl.php` for the profile content
* `page-user-register.tpl.php` set to match page.tpl.php in order to keep page-user.tpl.php from overriding the register page, and
* `page-user-login.tpl.php` set up in the same way as page-user-register for the same reason.

# Answer
> 4 votes
Try this...

```
page--user-profile.tpl.php

```

\[page\]--\[node\].tpl.php

or actually...

```
page--user.tpl.php

```

To see available templates for this page simply do the following in your themes template.php

```
function YOURTHEME_preprocess_page(&$variables) {
   echo '<pre>'; var_dump($variables['theme_hook_suggestions']); echo '</pre>';
}

```

If nothing were in there (doubtful), then just add your own...

```
if ($SOME_CONDITION) {
    $variables['theme_hook_suggestions'][] = 'page--user-profile.tpl.php';
}

```

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


# Question
Title: Content type with a field of multiple values of other content type (1-n relation)
What should be the approach for the common cases where we need a content type with a field of multiple values of other content type? The typical "*1* invoice as *n* invoice lines" where *invoice* is a content\_type and \*invoice\_line\* other content type. I did some research and I'm confused because there are: Relation, References, Entity References... (For Drupal 7)

Thank you.

# Answer
The Entity reference would be the best choice for your requirement. It is also a successor of the References module.

> References will most probably be deprecated in the near future in favor of Entity Reference, which should probably be considered first on fresh D7 projects.

The Relation module is more suitable for complex relationship. You can see this clearly in its module page:

> Relation is an API module and storage model for both simple and the most complex relations between entities. The module can handle both directional and symmetrical relations very well.
>
> Relations are entities and can therefore have fields. This makes Relation the most flexible and powerful relation model out there.
> 1 votes

---
Tags: nodes
---


# Question
Title: Create node and node reference from URL at one time
I have content type "article", in some cases I need to orginise group of parent and child nodes and to do this I use Node Reference from URL module. Also I need to include parent node in this group of articles because some views and node URL depend on completed field "node reference". So, how it works now:

1. I create a parent node and leave the node reference field empty as the parent node doesn't exist now;
2. Save this node
3. Back to edit page and choose my new parent node from the list of avalible nodes in node reference field;

What I would like to do is to create parent node and fill node reference field at the same time.

I guess that Rules module could help me but It too powerfull module and I do not need it for my website. Is there a more simple solution?

# Answer
Use `hook_node_insert` and update the node.
> 2 votes

# Answer
Depending on which relationship module you're using there are different options.

* If you're using Entity Reference there's the Inline Entity Form module:

> Provides a widget for inline management (creation, modification, removal) of referenced entities. The primary use case is the parent -\> children one (product display -\> products, order -\> line items, etc.), where the child entities are never managed outside the parent form.
* If you're using the References module there's References Dialog:

> This module extends reference fields like the user and node reference fields by adding links to add, edit and search for references through a dialog. This allows for a workflow where the user can create all the references to a node at the same time as she is creating it, a process which sometimes get's a bit backwards, when a user for instance needs to create all the facts for an article.

Both will allow you to create a referenced node at the same time as creating the referee.
> 5 votes

---
Tags: 7, nodes
---


title: How to rotate views in module?

text:
# Question
Title: How to rotate views in module?
I have created a views that works as a slider (title, image, read more).

And now I need some slideshow sow it rotates the views content from newsest to oldest with some transition animation.

I want to use the existing Views I have created and styled already, just to fade out fade in or some more fancy animation.

Any advice how to do that? Any views additional module that can do that?

# Answer
Try Views Slideshow

> 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.
> 2 votes

---
Tags: views, javascript
---


title: Insert block above comments in node

text:
# Question
Title: Insert block above comments in node
How to display block in node above comments. What i have tried is: create region - `regions[above_comments] = Above comments` after in *template.php* i have added this to `THEME_preprocess_node`

```
$variables['above_comments'] = theme('blocks', 'above_comments');

```

and in my node.tpl.php i have added this below `print render($content);`

```
<?php if ($above_comments): ?>
   <?php print $above_comments; ?>
<?php endif ?>

```

Added my content to this region, but its still empty, `dpm($variables['above_comments'])` \- - is empty. What is wrong?

# Answer
> 2 votes
`theme_blocks()` was only available for Drupal 5 & 6, which is why your code isn't working.

The D7 equivalent is `block_get_blocks_by_region()`, e.g.:

```
$variables['above_comments'] = drupal_render(block_get_blocks_by_region('above_comments'));

```

# Answer
> 0 votes
If you are in 7: Commentsblock or even in 6: Comment block

Separate comment from node, then place your block above of comment block

# Answer
> -3 votes
See `node.tpl.php`

Check where it prints `<?php print render($content['comments']); ?>`

Just render your region before `<?php print render($content['comments']); ?>`

---
Tags: blocks, theming
---


title: No Result from taxonomy API function

text:
# Question
Title: No Result from taxonomy API function
I want to output all the node IDs which belong to a taxonomy term ID. I use the following code in page--taxonomy.tpl.php.

```
$a = taxonomy_select_nodes(arg(2), $pager = TRUE, $limit = FALSE, $order = array('t.sticky' => 'DESC', 't.created' => 'DESC'));

```

When on the parent term page, `print_r($a)` shows an empty array. Why does this happen?

Under the parent term, there are two child terms which have some articles. How do I get the node ID?

# Answer
> 2 votes
taxonomy\_select\_nodes() is returning an empty array because there aren't nodes using that taxonomy term, since that function doesn't return the nodes using any children of the taxonomy term passed as argument. This is also what a taxonomy term page does.

It could be the database table used from the function doesn't contain any data, simply for the fact the *taxonomy\_maintain\_index\_table* persistent variable is not set to `TRUE`. If that is the case, then `variable_get('taxonomy_maintain_index_table')` returns `FALSE` (or an equivalent value). A persistent variable can be overridden from the settings.php file; that is the reason I am not suggesting to check the database.

As side notes:

* The page--taxonomy.tpl.php template is used not only for `taxonomy/term/<term id>`, but for any path under taxonomy, for which there isn't a taxonomy term associated. I would rather use page--taxonomy--term--%.tpl.php that is surely associated with a taxonomy term.
* If you are calling a function, and want to use the default value for some of its parameters, just leave them off. Instead of calling `taxonomy_select_nodes()` as `taxonomy_select_nodes(arg(2), $pager = TRUE, $limit = FALSE, $order = array('t.sticky' => 'DESC', 't.created' => 'DESC'))`, call it as `taxonomy_select_nodes(arg(2))`. What you are doing is assigning `TRUE` to the `$pager` local variable, `FALSE` to `$limit` (another local variable), and an array to `$order`; those values are also passed as arguments to the function. So you are setting local variables to pass arguments to a function, and you are passing the default values for those arguments. Keep in mind that in PHP, a function arguments are only positional, differently from Ruby, for example.

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


title: Duplicated content on homepage

text:
# Question
Title: Duplicated content on homepage
I've found that my site is showing duplicated content, I think it was when I installed Pathauto. The nodes are not duplicated though but seems to be multiple aliases.

I've since tried using Global Redirect but it hasn't solved the issue. And even worse, some items are showing up three times now!

For example

http://biosphericproject.php5.demo.faelix.net/content/what-we-mean-forest-gardening-1 http://biosphericproject.php5.demo.faelix.net/content/what-we-mean-forest-gardening http://biosphericproject.php5.demo.faelix.net/content/what-we-mean-forest-gardening-0

Confused, Alex

# Answer
> 0 votes
You have to delete those duplicate alias by going to the alias list at admin/config/search/path (in Drupal 7). It's not an automatic task, I'm afraid. Or you can delete all alias and bulk recreate them using the Bulk Update function. That would be an automatic process.

As a last step, you should check Alias Settings at admin/config/search/path/settings. I think you should change the "Update action" to "Create a new alias. Delete the old alias.".

---
Tags: path-aliases
---


# Question
Title: How to theme a select box with multiple selection enabled
I have a select box with multiple selection option enabled in my custom form. Everything is works fine, however the problem is the appearance is not good and also If I have more options then the selection becomes difficult.

Is there any module out there which offers left-right selection widget like below

or any other better solution which offers better user friendly selection for select box with multiple selection option enabled.

Hope there is an easy way to achieve this rather than writing custom CSS, jQuery/JavaScript code.

# Answer
I hope you are looking for this Multi Select module.

> The Multiselect module defines a widget to be used with CCK fields. It allows the user to select multiple items in an easy way. It consists of two lists, one of all available items, the other of selected items. The user can select an item by moving it from the unselected list to the selected list. This module relies on the built-in jQuery features of Drupal and does not require any additional modules other than the CCK module set (Drupal 7 version has no dependencies).
> 1 votes

# Answer
The Improved Multi Select widget sounds right up your street:

> The Improved Multi Select module replace the default multi-select boxes with two pannel list and search.
>
> The first panel holds the options that are available, and the second panel holds the options that have been selected.

It looks pretty good too:
> 2 votes

# Answer
Other than the modules listed above, here is the few others,

1. jQuery UI Multiselect
2. Multiple selects
3. Chosen
> 1 votes

---
Tags: 7, forms
---


# Question
Title: Drupal content slider like ImageFlow and GalleryFormatter
I am looking for Drupal modules that allows to create content sliders (img,audio,video) like ImageFlow and GalleryFormatter.

But those modules supports only images.

Are there any modules for creating content sliders like above?

# Answer
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.
> 1 votes

# Answer
You could also take a look at Nivo Slider project.
> 0 votes

---
Tags: 7, javascript
---


title: Embedding a YouTube channel

text:
# Question
Title: Embedding a YouTube channel
Recently i did small project for a community now their requirement is to include a block that contain a YouTube video frame and they have to display their YouTube channel there, So i have installed emfield module but i don't know how to implement that. Is there any suggestion like which module is comfort for these purpose ? and How to use emfield ?

# Answer
> 1 votes
As far as I know, every YT-channel has it's own embed code. Try to embed this code to your block and make sure "Full HTML" is set as text-format.

Look here as well: Embed You-Tube channel

---
Tags: 7, files, nodes
---


title: node_load get blank

text:
# Question
Title: node_load get blank
My `page.tpl.php` structure is:

```
<ul>
    <li id="creative-events">
    <div class="info animate-in">
    <?php node_load($nid = 10); ?>
    </div>
    <img class="sky animate-in" src="themes/bc/imagesx/bc_1.png" alt="Blue Sky" />
    <img class="balloon animate-in" src="themes/bc/imagesx/balloon.png" alt="Balloon" />
</li>

```

But not found my node. It's like this on Firebug:

```
<div class="info animate-in" style="">
                                            </div>

```

# Answer
I've used this codes and working!

```
$view_mode = 'teaser'; // Or 'full' for example

$node = node_load(1473);

$view = node_view($node, $view_mode);

print render($view);

```

But still want to know where I went wrong.
> 0 votes

---
Tags: 7, nodes
---


# Question
Title: Create a field linked to a vocabulary with Drush
Let's say I have created a taxonomy vocabulary called `ABC`. For this vocabulary `ABC`, i want to create many fields using Drush.

I've tried

```
drush field-create ABC myfield,text,text_textfield

```

It works, doesn't give any error, but if I go to the admin panel, I click on `structure => taxonomy` then in the list I see `ABC`, I click on "`Edit`" then I click on the tab "`Manage fields`" where I **expect** to see my field. Because (correct me if I'm wrong) I think that the drush command line `field-create ABC myfield` should have added it. But no.

It's not there. But if I click on the combo of the "`Add existing field`" option, in the list, there's the `myfield` that I've just created!

It seems there "link" between `ABC` and `myfield` is not created. `myfield` is created, but it's not "included" in the `ABC` fields.

Am I doing something wrong, or missing something?

# Answer
> 5 votes
You are missing Entity type. See the documentation from drush

> Create fields and instances. Returns urls for field editing.
>
> Examples: drush field-create article Define new article fields via interactive prompts. open `drush field-create article` Define new article fields and then open field edit form for refinement. drush field-create article Create two new fields.
> city,text,text\_textfield
> subtitle,text,text\_textfield
>
> Arguments: bundle Content type (for nodes). Name of bundle to attach fields to. Required.
> field\_spec Comma delimited triple in the form: field\_name,field\_type,widget\_name. If widget\_name is omitted, the default widget will be used. Separate multiple fields by space. If omitted, a wizard will prompt you.
>
> Options: --entity\_type Type of entity (e.g. node, user, comment). **Defaults to node.**

As you can see the entity type defaults to node . So you have to specify the entity type as taxonomy\_term.

> drush field-create ABC myfield,text,text\_textfield --entity\_type=taxonomy\_term

---
Tags: taxonomy-terms, entities, drush
---


title: Why isn't there any output?

text:
# Question
Title: Why isn't there any output?
```
$results = db_query("select nid from {taxonomy_index} where tid = :tid", array(':tid' => arg(2)));
foreach ($results as $result) {
  $node = node_load($result->nid);
  echo $node->title;
}

```

I put the code in page--taxonomy.tpl.php, but there is no result. Why?

The output of `print_r($results)` is the following one.

```
DatabaseStatementBase Object
(
    [dbh] => DatabaseConnection_mysql Object
        (
            [shutdownRegistered:protected] =>
            [target:protected] => default
            [key:protected] => default
            [logger:protected] =>
            [transactionLayers:protected] => Array
                (
                )

            [driverClasses:protected] => Array
                (
                    [SelectQuery] => SelectQuery
                )

            [statementClass:protected] => DatabaseStatementBase
            [transactionSupport:protected] => 1
            [transactionalDDLSupport:protected] =>
            [temporaryNameIndex:protected] => 0
            [connectionOptions:protected] => Array
                (
                    [database] =>
                    [username] =>
                    [password] =>
                    [host] =>
                    [port] =>
                    [driver] =>
                    [prefix] => Array
                        (
                            [default] =>
                        )

                )

            [schema:protected] =>
            [prefixes:protected] => Array
                (
                    [default] =>
                )

            [prefixSearch:protected] => Array
                (
                    [0] => {
                    [1] => }
                )

            [prefixReplace:protected] => Array
                (
                    [0] =>
                    [1] =>
                )

        )

    [queryString] => select nid from taxonomy_index where tid = :tid

```

# Answer
*Please confirm you got any value from arg(2) which is equivalent to term id(tid) .*

Try this code

```
$result = db_select('taxonomy_index', 't')
  ->fields('t')
  ->condition('tid', arg(2), '=')
  ->execute()
  ->fetchAssoc();

$node = node_load($result->nid);

print_r($node);

```
> 0 votes

# Answer
The taxonomy\_index database table just contains a list of the nodes using a taxonomy term, not that taxonomy term, and any of its child terms (or its parent terms). If there isn't any node that is using a taxonomy term, the code you wrote doesn't print anything.

If you want to get a list of node using a taxonomy term, or its child terms, you could use code similar to the following one.

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

$nids = db_query("select nid from {taxonomy_index} where tid IN :tids", array(':tids' => $tids))->fetchCol();

$nodes = node_load_multiple($nids);

```

The other reasons that could cause the code not to print anything are:

* The taxonomy\_index table is empty for some reasons, including the fact the Drupal variable taxonomy\_maintain\_index\_table is not set to `TRUE`. Check what `variable_get('taxonomy_maintain_index_table')` returns; if it returns `FALSE` (or an equivalent value), that would explain why the table is not populated.
* The value you are using as taxonomy term ID is not a taxonomy term ID.
* There isn't any node using the taxonomy term for which you have the ID.
> 0 votes

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


# Question
Title: How do I get the current year in the footer?
I want to put a copyright notice in the footer of my posts, and I want the year always to be current. I've tried adding

```
<?php echo date("Y"); ?>

```

to the Footer, but the actual code shows up; it doesn't get parsed as PHP.

How do I get the footer to display the current year?

# Answer
That happens because you are creating a custom block, but you didn't select PHP code as input format.

In Drupal 7, you need to first enable the PHP module (php.module); in Drupal 6, you need to first enable the input format on admin/settings/filters. Once you have done that, you will be able to choose PHP code as input format, and write PHP code between `<?php` `?>` tags; the code will be executed, and the output will be the content of the block.
> 5 votes

# Answer
Disable rich-text format and rewrite it correctly. In html format is symbols like \< or " are actually parsed as `&lt ;` and `& quot ;`. so rewrite it to the correct PHP code.
> 2 votes

---
Tags: theming
---


title: Batch Deleting Entity Types

text:
# Question
Title: Batch Deleting Entity Types
On one of my sites, I have over 600 Profile 2 profile types (most of them have between 20-30 field instances, some have additional fields just used in that one type). I've tested a few different methods for bulk deletion, but can't find a way using the Entity/Profile APIs to get the deletion to occur without basically wiping out the site for a few hours.

It seems that, when a content type, profile type, etc. is deleted, a ton of caches are cleared and rebuilt for each deletion, meaning the process goes something like:

1. Delete the entity type. (I do this part.)
2. All the attached field instances are deleted.
3. All the attached fields that have no other instances are deleted.
4. All the field info and entity caches are cleared.
5. All the caches are rebuilt (due to other visitors on the site trying to load pages which need those caches).
6. Ready to delete another entity type.

Is there any quicker way of mass-deleting entity types (I've already removed all the entities themselves—they're quite simple and fast to remove)? I'd like to cut out steps 4 and 5, which take about 90 seconds.

(I changed to a different system for storing profiles, because the cache rebuild and memory requirements were getting out of hand with over 500 profile types (in addition to 20 other content types), and over 10,000 field instances!)

# Answer
I decided to bite the bullet and run everything with Batch API. This meant the site was painfully slow for probably 2-3 hours, then slow for another hour or so. The profile type deletions became faster as there were fewer left to delete (since cache rebuilds were less intense the fewer field instances that were required).

I set up the batch using something like the following:

```
// You can remove the limit if you want, but this is a very long operation,
// so it's nice to do it in smaller chunks during traffic lulls.
$types = db_query("SELECT type FROM {profile_type} LIMIT 100")->fetchCol();
$batch = array(
  'operations' => array(
    array('mymodule_bulk_delete_profile_types', array($types))
  ),
  'finished' => 'mymodule_bulk_delete_profile_types_finished',
  'title' => t('Removing Profile Types'),
  'init_message' => t('Beginning profile type deletion...'),
  'progress_message' => t('Deleting profile types...'),
  'file' => drupal_get_path('module', 'fn_profile') . '/includes/fn_profile.utility.inc',
);
batch_set($batch);
batch_process();

```

Then, I had two batch callbacks (the processing function and the finished function), like so:

```
function mymodule_bulk_delete_profile_types($types, &$context) {
  $context['finished'] = 0;

  if (!isset($context['sandbox']['progress'])) {
    $context['sandbox']['progress'] = 0;
    $context['sandbox']['max'] = count($types);
    $context['results']['count'] = 1;
  }

  if (!isset($context['sandbox']['types'])) {
    $context['sandbox']['types'] = $types;
  }

  $key = $context['results']['count'] - 1;
  $type_to_delete = $context['sandbox']['types'][$key];
  $profile_type = profile2_get_types($type_to_delete);
  profile2_type_delete($profile_type);

  $context['results']['count']++; // Increment the counter.
  $context['finished'] = $context['results']['count'] / $context['sandbox']['max'];

  // Show message updating user on how many profile types have been deleted.
  $context['message'] = t('Deleted @count of @total profile types.', array(
    '@count' => $context['results']['count'],
    '@total' => $context['sandbox']['max'],
  ));
}

function mymodule_bulk_delete_profile_types_finished($success, $results, $operations) {
  // Display any warnings.
  if (!empty($results['warnings'])) {
    foreach ($results['warnings'] as $warning) {
      if ($warning) {
        drupal_set_message($warning, 'warning');
      }
    }
  }
  // Set operation successful message.
  if ($success) {
    if ($results['count'] == 0) {
      $message = t("No profile types were deleted.");
    } else {
      $message = t("@count profile types deleted successfully.", array('@count' => $results['count']));
    }
  } else {
    $message = t("There were problems deleting profile types.");
  }
  drupal_set_message($message, 'status');
}

```

At the beginning, it was taking between 50 seconds and 80 seconds to delete a profile type. Towards the end of the batch, it was only taking about 20-30 seconds. The site now only uses about 30-40 MB (according to devel.module) when clearing all caches; it was using about 190 MB before, and taking over 2 minutes to rebuild the caches!
> 1 votes

---
Tags: entities, batch-operations
---


# Question
Title: Export content type: 'An illegal choice has been detected. Please contact the site administrator.'
I have a content type which uses a lot of conditional fields, along with an email field, field permissions. When I try to export the type, it produced the error 'An illegal choice has been detected. Please contact the site administrator.' and the export script seems to be truncated so the fields do not import correctly. Any ideas what might be causing this?

# Answer
> 2 votes
This was caused by a corrupted field. I deleted and re-added the field.

---
Tags: nodes
---


title: Template file naming with alias

text:
# Question
Title: Template file naming with alias
I have a few template node overrides in my theme using Drupal 7.

For example: page--node--53.tpl.php

This might be a lazy request, but is there anyway to name these files instead with the alias I have chosen rather then using the node number? That way I don't have to memorize all of the associated pages.

For example page--node--about.tpl.php

# Answer
Something like this in template.php should do the trick:

```
function MYMODULE_preprocess_page(&$vars) {
  if ($node = menu_get_object()) {
    $alias = drupal_get_path_alias("node/$node->nid");

    // Remove slashes from the potential filename
    $clean_alias = str_replace('/', '__', $alias);

    $vars['theme_hook_suggestions'][] = 'page__node__' . $clean_alias;
  }
}

```

You might need to massage your `$clean_alias` variable a bit more to handle any punctuation you're allowing into aliases (e.g. with Pathauto).

A node with an alias like `about/about-us` would then use a template file called `page--node--about--about-us.tpl.php`.
> 1 votes

# Answer
In THEMENAME\_preprocess\_page (in template.php located in your themes directory) you can set as many template hook suggestions as you wish. Drupal then goes through the list from bottom to top and once it finds the existing template suggestion, it stops and uses that one.

```
function THEMENAME_preprocess_page(&$vars) {
  // Add theme hook suggestions based on path for nodes only.
  if (isset($vars['node'])) {
    // get whatever you want here into $path variable
    $path = $vars['node']['type'];
    $vars['theme_hook_suggestions'][] = 'page__node__' . $path;
  }
}

```

in the $vars there should be the node object that you can check for $vars\['node'\]. also don't forget to sanitize anything you are adding there. good choice would be to use the drupal\_clean\_css\_identifier function
> 3 votes

# Answer
You should look at this thread in which someone has implemented this kind of template suggestions.
> 0 votes

---
Tags: theming
---


# Question
Title: Create new content of a different type within the article edit screen?
My editors are asking to be able to create content of different types (albums, songs) from the same screen they use to edit articles. Are there any modules that support this type of functionality?

# Answer
> 0 votes
The Inline Entity Form should help assuming the content types need to reference each other as well!

> Provides a widget for inline management (creation, modification, removal) of referenced entities. The primary use case is the parent -\> children one (product display -\> products, order -\> line items, etc.), where the child entities are never managed outside the parent form.

It was created primarily for Drupal Commerce (Product display -\> Product references on one page), but the functionality is there for other entities (out of the box it supports nodes, so it should be fine for your needs).

(Assumed) use case:

* Add an entity reference for Songs onto an Album content type
* Configure the entity reference to use the inline entity form (IEF) as its widget
* Add an album - from here you can add songs to the album using the IEF
* When you save the Album, it'll create the Album node plus all of the Song nodes and keep an Album-\>Song reference

---
Tags: 7, nodes
---


# Question
Title: How to disable creating links for content types?
I don't want my slideshow text and image to be accessible in url (it is a contentype called slider).

Because normaly nobody will access that, but if he knows the url he can access that and also google bot etc.

I am using this content type only in Views Block.

I don't need pages.

How to do that?

Any module or template?

# Answer
> 4 votes
I always use the Rabbit Hole module in this situation.

> Perhaps you have a content type that never should be displayed on its own page, like an image content type that's displayed in a carousel. Rabbit Hole can prevent this node from being accessible on its own page, through node/xxx.

You can set redirects from the pages too, so you can add a 301 or a 404 (for example)

---
Tags: views
---


# Question
Title: If there is no nodes in current taxonomy term to display, load vocabulary and display other
*difficult to formulate a question*

I have made a View, which display `title, image, body(trimmed)` on nodes pages with Content type - `Home`, its related nodes to this one(. `Home` has different categories - taxonomy, for example looks like this:

1. Homes one
2. homes two
3. homes three

So for example if my current node has taxonomy term - `homes two` i should display only nodes`(title, image, body(trimmed)` of this term. I did it like this - with *contextual filters* `Content: Nid` \- i exclude current node to not display it in my view and

```
Content: Has taxonomy term ID

```

When filter is not available - i provide my own value, php code:

```
 $node = node_load(arg(1));
 if($node) {
 foreach($node->field_home_category[LANGUAGE_NONE] as $term) {
    $terms[] = $term['tid'];
 }
    return implode('+',$terms);
  }
  else {
    return
  }

```

`$node->field_home_category[LANGUAGE_NONE]` \- is a field which contains taxonomy term id.

And its works fine, but if my node is only single in `homes two` taxonomy term, the view returns nothing(for obvious reasons) and if this happens i need to display any other `Home` nodes.

I think i should load my taxonomy vocabulary and get all the terms and pass them to my view in this situation. Like this:

```
$tree = taxonomy_get_tree(2); // vocabulary id - is 2
    foreach ($tree as $term) {
        $options[] = $term->tid;
      }
      return implode('+', $options);

```

**but i dont know how to add this to my view.**

Something like this -\>

**PSEUDO CODE:**

```
IF THERE IS NO NODES IN CURRENT TERM
   DO
      LOAD VOCABULARY OF HOMES
    AND
      DISPLAY ANY AVALIABLE NODES OF THIS VOCABULARY

```

//////////////////////////////////////////////////////

**I will post full solution, maybe helps someone:**

//////////////////////////////////////////////////////

No results behavior is great, but there is few situations:

For example:

```
homes two contains 2 homes, one is excluded, so view will display only 1 home, but we need 3 homes to be displayed all the time.

```

What i did is created new view, which displays 3 homes randomly(global Random sort criteria) and excluded `nid` in contextual filter, i allow to pass multiple values to `nid`. and in `THEME_views_pre_render(&$view)` i did next thing:

```
function THEME_views_pre_render(&$view) {
  if ($view->name == 'home') { // check is this my view
      $args = $view->args; //passed arguments
      $results = &$view->result; // this is important , you should pass it by reference
      if (!empty($args) && isset($args[0]) && isset($args[1])) {
        $node = node_load($args[1]);
        if ($node->type == 'home') { // check node type
            foreach($view->result as $row) {
                $restricted[] = $row->nid; //push current nodes to array, to pass them later to our new view, to not display them
            }
            $result_count = count($view->result);
            switch ($result_count) {
                case 1: // if one home
                    //gett the results of my view which display all nodes
                    // and do not display node which already displayed
                    // aka $restricted array
                    $result_array = views_get_view_result('related_homes_and_features', 'block_3', $restricted);
                    //add this results to current view
                    //
                    array_push($results, $result_array[0],$result_array[1]);
                    break;
                case 2:
                    $result_array = views_get_view_result('related_homes_and_features', 'block_3', $restricted);
                    array_push($results, $result_array[0]);
                    break;
                case 3:
                    $result_array = views_get_view_result('related_homes_and_features', 'block_3');
                    array_push($results, $result_array[0], $result_array[1], $result_array[2]);
                    return;
                    break;
            }
        }
    }
  }
}

```

home that helps someone.

# Answer
> 4 votes
Use **"No results behavior"** of the view ; specify a new view ("Global: View area"), showing all nodes, *excluding* the taxonomy term "homes two".

---
Tags: views, nodes
---


# Question
Title: Output the width & height of an image using a particular image style
In Drupal, you can use the following in a `field--field-image.tpl.php` file to output an image as a URL using a particular image style:

```
<?php foreach ($items as $delta => $item): ?>
<?php echo image_style_url('thumbnail', $item['#item']['filename'] ); ?>
<?php endforeach; ?>

```

This will output all images as a URL with the Thumbnail style.

I would like to get the width and height values of that image (with the thumbnail style). How can I do it?

I would like to do it without having to install any extra modules.

# Answer
> 3 votes
image\_get\_info() is the function that will get you the details. But it accepts uri as the param (Not sure about url). You can try passing the argument. If you manage to get the path of the images then this function return the following ,

* "width": Width, in pixels.
* "height": Height, in pixels.
* "extension": Commonly used file extension for the image.
* "mime\_type": MIME type ('image/jpeg', 'image/gif', 'image/png').
* "file\_size": File size in bytes.

# Answer
> 2 votes
The correct API your looking for is imagestyle\_transform\_dimensions.

> Determines the dimensions of the styled image.
>
> Applies all of an image style's effects to $dimensions.
>
> Parameters
>
> $style\_name: The name of the style to be applied.
>
> $dimensions: Dimensions to be modified - an array with components width and height, in pixels.

I have used this in code to specify CSS `width` values in field templates (I also used imagecache\_proportions which is a pretty cool module).

For example from a field template file. This code in better placed in a preprocess theme function, i was in a hurry :)

```
// file field--field-aux-images.tpl.php
#dpm($items, 'items');
#dpm($item_attributes, 'image_attributes');
#dpm($attributes, 'attributes');

// my field cardinality was 1.
$dimensions = array(
  'width' => $items[0]['#item']['image_dimensions']['width'],
  'height' => $items[0]['#item']['image_dimensions']['height'],
);
#dpm($dimensions, 'default image dimensions');

$dim1 = $dimensions;
$dim2 = $dimensions;
$dim3 = $dimensions;
// $dim1 .. $dim3 contain the final dimensions of the original image
// having been virually run through the named image style.
image_style_transform_dimensions('ccs_news_events_teaser_square', $dim1);
image_style_transform_dimensions('ccs_news_events_teaser_wide', $dim2);
image_style_transform_dimensions('ccs_news_events_teaser_tall', $dim3);

// ... some other code
$computed_width_style = 'style="width: '.$dim1['width'].'px;"'

```

---
Tags: 7, theming, media
---


title: Using views in a clever way?

text:
# Question
Title: Using views in a clever way?
I would love some help to think here, I need to create one or several views (I'm hoping one)

I have a site that will present different groups and they will each have their own page/view with: \- a slideshow \- some nodes \- a contact form \- a block with Facebook posts from their Facebook pages \- some social links (like google+, Facebook like etc.)

I will start with a few but I want it to be easy to add more in the future, hopefully without creating a new view for each group. Note that this is not a social site, the content will be added by one person and the page will simply be a presentation of these groups in a standardized way.

I'm thinking views with EVA and maybe I could use taxonomy to "group" them? I don't want to put a specific term if I don't have to as that would exclude any new groups and also would force me to make a separate view for each group. How would I go about to set it up in such a way that it recognizes what to show in one view?

Thankful for any insight and suggestion!

Drupal 7 (Multilingual site)

---

I will try to explain better.

* Let's say I have several products that I want to present in a standardized way: a slideshow, text with images, a contact form, content from a specific Facebook page, content from a specific twitter feed etc.
* This will be presented in a view.
* I have several products and I want to easily be able to add more, preferably without having to create a new view each time.

How do I go about it? If I use taxonomy to mark what belongs together I will still have to create a new view every time I add a new product. If I use content types I have to create a new content type for each product (which would be even more work).

# Answer
What I see here is a typical **Panels** situation, with **Taxonomy**.

1. Create a **vocabulary** *"groups"*,
2. Create two **content types** : *slideshow item* , *nodes* (with term relationship field to the vocabulary "groups", of course)
3. Three **fields to the terms** themselves (taxonomy terms have "cck-like fields" in core since Drupal7) : *email adress*, *Facebook widget*, *etc.*
4. Create **views** for each use: the slideshow, the nodes...
5. Enable the "*taxonomy term page*" **panel**, and insert in it your views showing your content associated to that term, and the fields of your term (Panels has the out-of-the-box interface for that) : contact form, FB block, and so on.

That's the simpliest I see :)
> 1 votes

# Answer
One idea could be to use Taxonomy Access Control. In my scenario I am using it to show from the same view different content to the users based on their role. What you need to do is to add to your content types an extra checkbox term reference field so when you go creating a new node you would also select which terms can have access to this node.

Don't know if this logic could also be implemented with Panels.
> 0 votes

---
Tags: 7, views, i18n-l10n
---


# Question
Title: How to display link to the next/previous most recent node from current node (if it does not belong to a book)?
I would like to display the next and the previous most recent node from the current node (if it does not belong to a node).

It is somewhat similar to the pager available to the book page, except here the current node as well as the links to the next/previous nodes are not in a hierarchy and do not belong to a book.

Assuming I have 4 nodes - node1,node2,node3,node4 (all belonging to a set of node types I want to use) and each published consecutively one after the other. Then if the user is on node3, he/she should see the links for node2 and node4. If currently on node2 then node1 and node3 links should show up. If they navigate to node1, then a link for node2 should be displayed and so on and so forth.

Also, the next and previous nodes can only belong to a pre defined set of node types.

I am using D7 and wouldn't mind using either a custom function or a views block to implement this. Any ideas on how to go about it?

# Answer
> 1 votes
You can do it with `db_query` in your `node--content_type.tpl.php`. Get all nids for content type in array. Match the current `nid` position in `array`. Like if Position is `array[3]` the Previous nid link should be `array[2]` and next should be `array[4]`.

# Answer
> 1 votes
You probably want to check the 3rd party contributed module called Previous/Next API

> Description
>
> This module allows you to know the previous or next nodes for any given node. This is very useful for providing navigational links to the user without the expensive queries required to dynamically deduce such information on the fly.
>
> Scalability
>
> Although the previous and next nodes can be deduced with some SQL work, the queries to do so are very heavy on the database, and can bring a site to its knees. This module solves this problem by storing the previous/next node in a table so lookups are fast. Once the module is installed, it will build this index backwards via cron until all nodes have been indexed. See the "More Info" section below for a detailed post on the positive scalability impacts of implementing this module.
>
> Configuration
>
> The module can be restricted to certain content types to be included in the previous/next indexing. For example, you want the site's visitors to browse through video and image nodes only, but not blogs and regular pages.
>
> The number of nodes to index is defined in the settings too. The default is 200, but you may want to lower that for a site on shared hosts. Once the indexing is complete for all the site's nodes, cron will do do anything. You can always reindex the site using the "Re-Index" button on the settings page.

# Answer
> 0 votes
I tried doing this using Views, but wasn't able to, so I wrote a function to achieve it. If someone has a better method of accomplishing the same, please do let me know. I am not that great with PHP, so if something can be optimised or needs fixing, I am all ears.

```
function pager_next_prev($nid,$type,$created,$nextOrPrevious)
{
    $rv=''; //return value
    //I don't want to show this pager on 'book' or 'page' content type
    if($type=='book' || $type=='page')
    {
        $rv='';
    }
    else
    {
        //here we check if the current node belongs to a book
        $doPrint=false;
        $queryForBID="SELECT b.bid from {book} b where nid=:nid";
        $result=db_query($queryForBID,array(':nid'=>$nid))->fetchField();
        $bid=0;
        if(null!=$result)
        {
            if($result!=0 || $result>0 || $result!='')
                $bid=$result;
        }
        if($bid!=0)
        {
            //if it does, then we return empty string
            $rv='';
        }
        else
        {
            //here we declare a set of valid content types using the machine names of the same
            $validTypes=array('set','of','valid','content','types');
            $queryForTitle="";
            $prepend='';
            //change query if we need the next or the previous most recent node
            if($nextOrPrevious=='next')
        {
            $queryForTitle="SELECT n.title title,n.nid nid FROM {node} n WHERE n.type IN (:types) AND n.created>:created LIMIT 1";
            $prepend='<<';
        }
        else
        {
            $queryForTitle="SELECT n.title title,n.nid nid FROM {node} n WHERE n.type IN (:types) AND n.created<:created ORDER BY n.created DESC LIMIT 1";
            $prepend='>>';
        }
        //fetch title and nid from DB
        $result=db_query($queryForTitle,array(':types'=>$validTypes,':created'=>$created));
                    $title='';
        if ($result)
        {
            while ($row = $result->fetchAssoc())
            {
                $title=$row['title'];
                $adjacentNid=$row['nid'];
            }
        }
            if(null!=$result)
            {
                //if no results found, return empty string
                if($title!='')
                {
                    //if some node is found, find it's url
                    $queryForURL="SELECT p.alias FROM {url_alias} p WHERE p.source=:source LIMIT 1";
                    $url=db_query($queryForURL,array(':source'=>'node/'.$adjacentNid))->fetchField();
                    //set return value
                    if($nextOrPrevious=='next')
                    {
                        $rv='<a href="http://www.whackk.com/'.$url.'">'.$prepend.$title.'</a>';
                    }
                    else
                    {
                        $rv='<a href="http://www.whackk.com/'.$url.'">'.$title.$prepend.'</a>';
                    }
                }
                else
                {
                    $rv='';
                }
            }
            else
            {
                $rv='';
            }
        }
    }
    return $rv;
}

```

---
Tags: paging
---


# Question
Title: Can you get any view to list content based on a field value?
I am trying to get a list view in a panels node template to show content based on a text field of the currently viewed node.

Just to give you more information I am including my setup below:

Content Type A - textfield called 'ref'. Content Type B - textfield called 'a\_ref'.

Content Pane View to show list of Content Type B but filtered depending on the node being viewed.

Node template on Content Type A with two regions (Left and Right).

On the Left I am displaying fields of the node being viewed. On the Right I want to show the Content Pane View with a list of Content Type B where 'a\_ref' is equal to 'ref'.

I am trying to figure out how to use contextual filters between the node template and content pane but to no avail.

I hope anyone out there can enlighten me on the way it should be done.

Thanks in advance for any help,

Kevin

# Answer
**Solution**

1. Get the view, and the view alone to do what you want. You need a *contextual filter* on the *field you want to match against*. Test the view out in the views UI.
2. Add a *content pane* display, this requires the views content module to be enabled. In the pane settings, find argument inputs settings (Sorry, no UI in front of me, that setting could be something else). In here you can tell Views what type of data the View should expect for the contextual filter. Pick *From context*. You'll be presented with a *looong* list of available options, it's easy to get this wrong, be careful. Scroll down until you under *Node* find the field you are trying to match against. If you have multiple fields with the same label, there is no easy way to know which is which. Yes, it's crap, you will have to go trial-and-error until this gets fixed. Save the view.
3. Go into Panels. Ensure that the new view is visible under the View *panes* category, *not* just *Views*. Add the view, tell it which node to get data from, which is usually just one, save.

**Troubleshooting**

This setup is non-trivial for a lot of users. I find that the common most problem people hit is configuring the view to require a certain type of input. If you can't get this to work, there are two things to try.

1. The Panels process for identifying which Views are valid, seemingly can get stuck sometimes. Clear caches, and resave both the View and Page.
2. In the Views arguments configuration, set the argument to be *optional*. This is not really what you want, but if this causes the View to show up in the Panels UI, then we know the problem is that Panels does not have access to the information that the View says it wants, which at least narrows the problem down a lot.
> 1 votes

# Answer
An alternative approach is possible using simply Views, Blocks and a bit of PHP inside the views configuration page.

Perhaps you could try using the views option 'Views Contextual Filter' and some inline php to set the default value for the contextual filter. The contextual filter allows you to use some PHP to rewrite the value passed to the filter.

I have to admit it does feel a bit like stepping back in time with Drupal and using PHP snippets, but it provides some nice configurability with only 'Views' and 'Blocks'.

My suggestion is to create a View listing 'Content type B' in a block.

Then add a contextual filter on 'a\_ref'. In the contextual filter select 'provide a default value' and 'php code'.

The php code will read arg(1), load up the node object and return the value of the field.

A quick way to test out the behavior of the contextual filter with default and PHP is with one link of php containing a static value, eg.

```
return 'some known for ref';

```

Then attach the block in the appropriate pages using normal block interface.

In one of my sites, I'm using this to parse the url, extract a numeric userid, and load the user object. I think you may be able to adapt this to load the node object instead and access the field that you require.

```
// snippet to include in text field in views default value, provide a value, php
if (arg(0) == 'user' && is_numeric(arg(1)) && arg(1) > 1) {
  // note - >1 not >0 so excludes admin

  if ($related_user = user_load(arg(1))) {
     return $related_user->mail;
  } else {
    return false;
  }
} else {
  return false;
}

```

Perhaps you could adapt this using node\_load() instead of user\_load(). A quick route would be to use $node-\>field\_ref\['und'\]\[0\]\['safe\_value'\] to access first value in this field.

I've not tried out using a multi value field - perhaps something along the following lines would work. This code below needs some further work, but it might get you started.

```
// snippet to include in text field in views default value, provide a value, php
$nid = arg(1);
if ($arg(0) == 'node' && is_numeric($nid) && $node = node_load($nid)) {

  // optionally add some more validation - $node->type or similar

  $field = field_get_items('node', $node, $field_name);
  $field_name = 'field_ref';

  if (count($field) > 0) {

    $output = array();

    foreach ($field as $delta => $f) {
      $value = field_view_value('node', $node, $field_name, $field[$delta]);
      // fix $value here using regexp or str_replace to replace unwanted slashes
      $output[] = $value;
    }

    return implode(', ', $output);
  } else {
    return false;
  }
} else {
  return false;
}

```
> 1 votes

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


# Question
Title: Mapping regular SQL to Drupal's Database API - using 'exists'?
I have the following SQL that I'm trying to translate using Drupal's Database API:

```
select nid,biblio_type from biblio where not exists
    (select * from biblio_types where biblio_type = tid);

```

What would the translation be? Currently I have this which is not working:

```
$sub_query = db_select('biblio_types','bt');
$sub_query->fields('bt',array('tid'))
         ->condition('biblio_type','tid','=');
$query = db_select('biblio','b');
$query->fields('b',array('biblio_type'))
      ->notExists($sub_query);
$result = $query->execute();

```

**EDIT #1**: Changed `exists` to `notExists`.

**EDIT #2**:

After changing `exists` to `notExists` and replacing the condition statement in the subquery with `where` per Clive's instructions, this is the SQL that is placed in `$result->queryString`:

```
SELECT b.biblio_type AS biblio_type
FROM
biblio b
WHERE  ( NOT EXISTS  (SELECT bt.tid AS tid
FROM
biblio_types bt
WHERE  (b.biblio_type = bt.tid) ))

```

...which is what I expect. If I place this statement verbatim in MySQL Query Browser I get the exact results I want. It returns exactly 9 rows of data. Perfect!

# Answer
> 1 votes
I think you'll need to use a `where()` for the condition in the subquery, PDO will most likely quote the 'tid' and mess it up.

```
$sub_query->where('bt.biblio_type = b.tid');

```

You can cast a `SelectQuery` to a string to view it's SQL equivalent at any time, it helps a lot with debugging the more complex queries.

```
print (string) $query;

```

---
Tags: 7, database
---


# Question
Title: Views Data Export: Multiple Columns with Unique Rows (D7)
I'm using Drupal 7

I have a view displaying users that are referenced by another entity that has a date field, like this:

**John Doe 5/6/12
John Doe 5/8/12
John Doe 5/16/12
Mary Jane 5/5/12
Mary Jane 5/7/12
**

So, behind the scenes, there's a content type of "Reservation" with a date field and a user reference field. I'm pulling in all of these reservations and displaying the user name alongside the dates of their reservations.

When I use the views\_data\_export module, I'm able to export this data as an xls file, which allows this data to open nicely in MS Excel.

The solution I'm looking for is to be able to group this data by user, to create unique rows with multiple columns, like this:

**John Doe 5/6/12 5/8/12 5/16/12
Mary Jane 5/5/12 5/7/12**

So, if a user has 20 pieces of data, then 20 columns will display next to that user with each column displaying each piece of data.

# Answer
> 2 votes
Have you noticed the following setting on the field which has multiple values:

That should be a collapsed section right under where you specify the label, etc of your field. Just make sure you check that you want them to appear in the same row and select a separator (comma by default).

That should be all you need! Does it transfer well for the export?

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


# Question
Title: Is theme('pager') designed to work only with dynamic query?
I have a custom callback function that queries data from a custom table.

The trimmed version of code that I have been writing looks as below,

```
function cb_user_cashback_orders($account) {
  $sql = 'SOME SQL QUERY';
  $results = db_query($sql, array(':uid' => $account->uid));
  //date, Merchant name, commission, status
  $header = array(t('Date'), t('Merchant Name'), t('Commission'), t('Status'));
  $rows = array();
  foreach ($results as $result) {
    $rows[] = array(
      format_date($result->timestamp),
      $result->status ? l($result->title, "node/{$result->merchant_nid}") : $result->title,
      $result->commission,
      $result->status,
    );
  }
  pager_default_initialize(count($rows), 10, 0); // Pager doesn't appear without this call
  $output = theme('table', array(
    'header' => $header,
    'rows' => $rows,
    'empty' => t('You have not made any purchase yet.'),
    'attributes' => array('class' => array('cb-user-orders')),
    )
  );
  $output .= theme('pager'); // as a replacement for pager_query() in D6.
  return $output;
}

```

I'm trying to figure out how I could get the pager work as expected.

With the code above I'm able to get the pager links (first, next, last, etc.) however the table always show the same set of items (infact all items) irrespective of pager argument (?page=1,2 OR N).

Would like to hear some input to fix this. Is theme('pager') designed to work only with dynamic query?

# Answer
> 1 votes
`theme('pager')` is not designed to work only with dynamic queries. The documentation for page\_default\_initialize() shows example code where dynamic queries are not used.

```
  // First find the total number of items and initialize the pager.
  $where = "status = 1";
  $total = mymodule_select("SELECT COUNT(*) FROM data " . $where)->result();
  $num_per_page = variable_get('mymodule_num_per_page', 10);
  $page = pager_default_initialize($total, $num_per_page);

  // Next, retrieve and display the items for the current page.
  $offset = $num_per_page * $page;
  $result = mymodule_select("SELECT * FROM data " . $where . " LIMIT %d, %d", $offset, $num_per_page)->fetchAll();
  $output = theme('mymodule_results', array('result' => $result));

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

```

The other example given in that documentation page shows code that uses an external service to retrieve information which is shown. Also in that case, dynamic queries are not used. (The external service could not even running Drupal.)

The only difference I can see between that code, and the PagerDefault class is that `PagerDefault` uses a unique ID that passes as last argument of `page_default_initialize()`.

```
/**
 * The unique ID of this pager on this page.
 *
 * @var int
 */
protected $element = NULL;

```

```
$total_items = $this->getCountQuery()->execute()->fetchField();
$current_page = pager_default_initialize($total_items, $this->limit, $this->element);
$this->range($current_page * $this->limit, $this->limit);

```

The other difference is that, as `PagerDefault` uses dynamic queries, its query can be altered with hook\_query\_alter(). In this case, as the added tag is *pager*, the query can be also altered with `hook_query_pager_alter()` which is a hook\_query\_TAG\_alter() hook.

```
  public function __construct(SelectQueryInterface $query, DatabaseConnection $connection) {
    parent::__construct($query, $connection);

    // Add pager tag. Do this here to ensure that it is always added before
    // preExecute() is called.
    $this->addTag('pager');
  }

```

---
Tags: 7, paging
---


# Question
Title: Adwords conversion tracking on Ubercart store with payment gateway?
is it possible to implement Adwords conversion tracking so that it takes into account conversion that come through payment portal (Customer leaves site for a moment and returns after payment, usually conversion is not tracked due leaving site for a moment)?

I have injected adwords tracking code to order completion page but it tracks only orders that come with billing option (customer does not leave the site).

If this is not possible, is it possible to inject code to order review page, if so how? (This is bad as some customers wont complete order so leads to false conversions. Also we are planning skipping order review page for billing)

# Answer
> 3 votes
You have to make users come back to your site adding this query string in the URL:

```
?utm_nooverride=1

```

Then Google will discard referral modification caused by leaving the site.

See this question.

You will have to deal with your payment gateway to modify the return URL, I think.

---
Tags: 7, ubercart, payment-gateways
---


# Question
Title: Addition to an integer field with a form
I have a bundle of image nodes of the same content type that I create in my custom form. Each image node has a field that contains a unique reference number to that node. Currently it is up to the user to add +1 to the previous image node saved and type that in the form for the next reference number. How can I add +1 to the last saved field and use the result to populate the saved field displayed on the saved node? More advanced: If I use an AJAX form that allows users to add more fields to add more pictures on the image creation form, how could I save the images with consecutive IDs?

# Answer
You can use the module Prepopulate ; latest release is dev but I use it on a production site and it works like a charm.

If it doesn't work tell me, there are two other solutions : send an arg in the URL to the form (and then use Panels or the php template) and JavaScript (I can give you the code if you need it).
> 0 votes

---
Tags: entities
---


# Question
Title: Passing a Taxonomy term via URL to add content form in Drupal 7
OK, I have a Drupal 7 site. And the scenario is that, let's say I'm on a page of my site that happens to have a taxonomy term assigned to it - let's say it's term ABC. Well in a block in the sidebar I have a link that sends the user to the ADD CONTENT form for a Forum Topic. The Form Topic content type has a CCK field as well (same vocab). I'm trying to automatically populate that field with the same term ABC as the page that they came from.

I was thinking this could be passed via URL as a GET parameter, but not sure if that would work and if so how to pull it off exactly.

# Answer
You can use the module Prepopulate ; latest release is dev but I use it on a production site and it works like a charm.

If it doesn't work tell me, there are two other solutions : send an arg in the URL to the form (and then use Panels or the php template) and JavaScript (I can give you the code if you need it).
> 1 votes

# Answer
You would use Views, and a contextual Filter. Taxonomy Term: Term ID. Then provide the value of the T.I.D.
> 0 votes

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