# Question
Title: What is the correct name to give to a taxonomy term page template file?
I have a taxonomy term page, which is not a view. It just lists all the content for the taxonomy. I would like to customize this page, and I have tried all permutations and combinations of names for the template file. The template file just won't work. I have tried page--taxonomy--term--5.tpl.php, page\_*taxonomy*\_term\__5.tpl.php.

What is the right filename to give to the template file, in this case?

I am using Drupal 7.

# Answer
I found that template.php file also needed a preprocess function for this to work:

```
function THEMENAME_preprocess_page(&$variables) {
 if ( arg(0) == 'taxonomy' && arg(1) == 'term' ) {
   $term = taxonomy_term_load(arg(2));
   $variables['theme_hook_suggestions'][] = 'page__taxonomy__term__' . $term->tid;
    }
}

```

then page--taxonomy--term--5.tpl.php works for a specific term
> 0 votes

# Answer
I use, for instance,

`page--taxonomy--term--6.tpl.php`

Make sure you **clear the cache** in Configuration \> Performance \> Clear all caches after creating your template.
> 3 votes

# Answer
You can use the theme developer module to find any template name or theme function. Just enable the module and point and click on the thing you like to theme differently.
> 0 votes

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


# Question
Title: Drupal 7 admin can't upload images, but all other users can
I'm experiencing a very strange error and I can't figure out what's causing it. I have a drupal 7 website and all users and roles can upload images without any issues, except user 1, the administrator. When I try to upload an image as user 1 to ANY content type or delete an already existing image it freezes or returns this:

"An unrecoverable error occurred. The uploaded file likely exceeded the", the strange part is admin has all the permissions and I disabled the admin menu and other modules that are unique to being user 1. Any ideas? It's driving me crazy.

# Answer
i guess you reached the upload limit for user 1, are you using IMCE ?
> 2 votes

---
Tags: 7, media, files
---


title: Drupal sign up code

text:
# Question
Title: Drupal sign up code
If a user does not have a Sign Up code they can enter the email address in which case they enter a user processing status. A user in this process with receive 4 pre-written emails as below

1. Email Template 1 sent after 1 day
2. Email Template 2 sent after 3 days
3. Email Template 3 sent after 5 days containing a sign up code
4. Email Template 4 sent after 10 days only if eMail Address has not joined

In drupal how we can do this functionality? is there module for this?

# Answer
> 2 votes
You can set up an e-mail scheduling workflow with the rules module. You can watch a screencast on how to set up rules scheduling here.

EDIT: If you are completely new to rules, the Node One screencast starts here.

---
Tags: hooks, users
---


title: Using hook_theme_registry_alter()

text:
# Question
Title: Using hook_theme_registry_alter()
I am using `hook_theme_registry_alter()` in my custom module for overriding the theme function. I have done something like this in my module file aml.module

```
function aml_theme_registry_alter (&$theme_registry) {
  $theme_registry['aml']['function'] = 'theme_menu_item_link';
  dsm($theme_registry);

}

function theme_menu_item_link () {
  drupal_set_message("hello");
}

```

I don't know how and where to implement this function **theme\_menu\_item\_link**

# Answer
I think you are trying to alter a `$theme_registry['aml']['function']` which doesn't exist.

Try have a look through the `$theme_registry` array, and find what you want to override, put this in where you currently have "\['aml'\]". I am guessing you want "\['menu\_item\_link'\]", but you will have to check.

Then change `theme_menu_item_link` to `aml_menu_item_link`.
> 0 votes

---
Tags: hooks
---


title: What are Panes, in a Übercart context?

text:
# Question
Title: What are Panes, in a Übercart context?
I was wondering what are "Panes" - I found them while I was messing with source code of *Ubercart* module. It looks like they're building page with something like panes - which I'm totally new to. Code looks like:

```
  // Load through the cart panes...
  foreach (uc_cart_cart_pane_list($items) as $id => $pane) {
    // If the pane is enabled...
    if ($pane['enabled']) {
      // Add its output to the cart view.
      $build[$id] = $pane['body'];
      ...

```

So, are "panes" Ubercart concept, or some in-general thing? I searched with "Drupal Panes" but no luck.

# Answer
Visit your checkout page (add product to cart, visit cart, then click Checkout), each fieldset (as in image) is a pane. It's not the same as for "panels" pane.
> 0 votes

---
Tags: 7, ubercart
---


# Question
Title: What are the appropriate configurations for the Subdomain module on Window 7 running XAMPP?
I have installed the Subdomain module (v 6.1.7), and I'm configuring a subdomain for testing on localhost.

I have been tearing my hair out for days now, trying to get this module to work on my PC - and I'm still stuck on the settings/configuration stage. I have scoured the web for help in vain, and now I'm appealing for help here.

My vital stats: Win7, XAMPP, Drupal 6, Subdomain 6.17. (I gave up on 6.2 because it turned my links into www.localhost/....)

My site is localhost/ideastar.

Here are the changes I have made:

### settings.php

```
$cookie_domain = '';

```

Leaving this commented out gives me an error ("The $cookie\_domain variable in settings.php is not set".)

Uncommenting and putting in "localhost", ".localhost", "ideastar", ".ideastar" gives me an "Access denied" error.

It seems to accept "localhost/ideastar" or a blank ' ', although I don't know if this is the right thing to do.

### host

```
127.0.1.1   localhost  ideastar

```

(and I can successfully ping ideastar)

### http.conf

```
NameVirtualHost *:80
<VirtualHost *:80>
ServerName ideaster
ServerAlias *.ideastar
DocumentRoot C:/xampp/htdocs
</VirtualHost>

```

Can someone please help me get past the following errors?

### Subdomain Prerequisites

> To enable subdomains on your website, you must first configure the following 5 items. If something isn't working, refer to the suggested solutions and make sure you have completed each step outlined in readme.txt.
>
> DNS server show/hide details: Not working yet
> test-1.localhost: Failed to resolve
> test-2.localhost: Failed to resolve
> test-3.localhost: Failed to resolve
>
> It appears your DNS server is not setup to handle wildcard subdomains (\*.localhost) for localhost. Edit the DNS zone file or settings for your server to fix.
>
> PHP caches DNS lookups, so you'll want to restart your web server after making changes to your DNS server to see the results of your changes on this page.
>
> Web server: Unable to test Unable to test Apache settings until DNS wildcard subdomains are working Drupal's inbound URL rewriting - show/hide details: Not working yet
> HTTP request to http://subdomain-test.localhost/ideally/subdomain/test resulted in an internal Drupal path of . It should have been ~subdomain-test/subdomain/test The `custom_url_rewrite_inbound()` function in settings.php is rewriting the internal path incorrectly. Did you patch settings.php? See readme.txt for instructions.
>
> Drupal's outbound URL rewriting - show/hide details: Working
> Drupal API: url('~subdomain-test/subdomain/test') returned 'http://subdomain-test.localhost/ideally/subdomain/test'
> $cookie\_domain in settings.php - show/hide details: Set
> The $cookie\_domain variable in settings.php is set to ''

# Answer
> 0 votes
I think you have to setup a *virtual host* in *XAMPP* having a different IP, like `127.0.1.2` and adjust your *host file* by adding `127.0.1.2` sub.ideastar.

More here (but in german.)

---
Tags: 6, subsites
---


# Question
Title: When a user login fails, is it possible to say "Password incorrect" or "Username does not exist" instead of the default message?
When a user types an incorrect user name or password, by default Drupal gives this message: "Sorry, unrecognized username or password."

To help my sometimes clueless users (and my clueless self), I'd like to provide more helpful messages to specify exactly what is wrong.

In other words:

* Incorrect password= "The password you provided is incorrect."
* Account does not exist= "No account is registered for USERNAME."

How could I go about doing this?

# Answer
This message is set in `user.module` in the user\_login\_final\_validate() function. It's set as a bog-standard `form_set_error()` so can't really be over-ridden. Looking at it, it also doesn't differentiate between whether or not the username or password is incorrect, so you wouldn't really be able to do anything useful.

As Clive mentioned, it's much better practice to keep a degree of ambiguity in certain error messages, and seeing as how this isn't wrapped in any kind of theme function and doesn't have separate behaviours for whether the username exists or password was incorrect, you're probably better off leaving it as is.

One last option you have is to user a `hook_form_alter()` on `user_form` to set an extra validation callback, and then check for the user name yourself.

Example:

(I can't remember the $form\_state for the user form, so you'll have to `die()` or `dpm()` that yourself)

```
function mymodule_check_username_exists($form, &$form_state){
  $user_exists = user_load_by_name($form_state['name']);

  if ($user_exists == FALSE ) {
   form_set_error('name', t('This username does not exist'));
  }
}

```
> 5 votes

# Answer
Have you check `user_login_authenticate_validate()` and `user_login_final_validate()`

I think you can work your way using anyone of those.

Hope that helps.

Muhammad
> 0 votes

---
Tags: 7, users, forms
---


# Question
Title: CKeditor - Edit form doesn't show anything in a <code> tag
Using ckeditor module + ckeditor 3.6.

I am using the 'full' text format as a admin role and when I initially fill out a text area and use the 'font styles' dropbar to make the text into 'code' html tags I can see everything great. When I save it, it comes out just like I wanted to.

But if I go back and edit the node (say a article node) I am not able to see any of the text that is between the code tags in the editor. When I click on 'plain text' format, I can see the code tags + text just fine.

If I save it with the 'full' format and I can't see the text in the editor, it still comes out fine on the page view. What could be the reason I can't see anything in 'code' tags in the edit form? All other ckeditor 'font styles' work fine.

# Answer
It is a issue with the CKeditor module it appears. If I use the styles dropdown menu for 'Computer Code' save it and then edit it, the text will disappear in the editor. If I disable the editor, I can see the code tags again.

I removed the CKeditor module and enabled and configured the wysiwyg module and now there is no issue. The text in between the code tags appear in the editor just fine now.
> 1 votes

# Answer
The `<code>`tag is probably stripped because it's not an allowed HTML tag. Please check the properties of your input format in `admin/config/content/formats` and check that `Limit allowed HTML tags`is unchecked.
> 1 votes

---
Tags: 7, wysiwyg
---


# Question
Title: How to select Google Web Fonts (via @font-your-face) from drop down in SWeaver UI?
I am using the SWeaver module for "in-situ" editing of the (CSS) styles of elements on pages i.e. by "in-situ" I mean *within* Drupal style changes (instead of raw editing the theme files CSS via FTP).

Sweaver provides the means to change the font of the text on a page via it's pop up user interface panel that resides at the base of the page.

I am trying to get the Google Web Fonts listed in the drop down menu of available fonts but this does not show. Apparently, Sweaver provides support for various web font foundries including Google Web Fonts via @font-your-face. So I've gone into the Admin/Configuration for @font-your-face and enabled Google Web Fonts and enables the fonts I want but they don't appear in the Sweaver drop down list.

Can someone supply a step-by-step guide to getting Google Web Fonts to appear in the drop down list of fonts in Sweaver

References:

# Answer
There should be a solution in the issue queue for SWeaver; several other users have reported similar problems. 2 things to try would be to clear the cache and to install the latest development version.

http://drupal.org/project/issues/sweaver?text=%40font-your-face&status=All
> 0 votes

---
Tags: 7, theming
---


# Question
Title: What top tips you have for designing drupal themes?
I would like to use a 960 grid system master theme to create my own custom Drupal 7 subtheme for generic audience.

What should I consider when designing professionally looking Drupal themes ?

What is the most important when designing with end user experience in mind ?

# Answer
> 3 votes
All you need is a consistent architecture and good planning. I think getting started on a HTML5 foundation is a good beginning. I suggest you build your project on a subtheme based on Omega or Fusion Theme kits.

Omega has a based on 960 grid system (12,18,24 columns, 20px gutter). It uses the zone/region relationship for a better block handling. Of course is a responsive theme, it starts mobile to desktop (not viceversa) which is very good.

You can even copy Omega subtheme page layout settings, alter it and save it under a new template with Delta module (created by Jake Strawn). Your settings can be then used in various context using the Context Module.

This is a good architecture to start with.

As a UX designer keep in mind Drupal is jQuery and jQuery UI ready, so learn to manipulate widgets via a module or a js (added in your info file).

Keep a consistent architecture and never mess with modules that are not necessary and only bloats your site.

In additional a good knowledge of Views module, contextual filters and relationships is a must.

# Answer
> 2 votes
I would highly recommend looking into using Responsive Web Design as suggested here for creating themes for mobile devices. That would be my top suggestion at least: A clean theme that would port easily from one system to the next, e.g. from desktop to phone, would probably be my most installed theme, especially since I am absolutely horrible at theme building.

# Answer
> 2 votes
I think Omega takes a good modern approach to a Drupal Theme, check it out for some inspiration. Omega mixed with Delta and Context is a very powerful combination.

I would also try and use HTML5 and maybe check out the HTML 5 boilerplate

If you are looking at designing polished and finished themes as opposed to a starter theme, some good examples can be found at at the rocket theme demos

# Answer
> 0 votes
+1 For your answer and +1 for the Accepted answer.

Here's some supplementary material to consider - these would help answer your question as well.

I've favourited your question as I may consider creating an Omega subtheme and I am including my own research here too.

---
Tags: theming
---


# Question
Title: Drupal 7: View filters impact on performance
Does having multiple view filters affect the overall performance of the site. for example having a category and search filter on main pages of articles and galleries?

# Answer
In general having more views will effect the performance of your site. However you can check the view query / render etc at the bottom of the view edit pages which should give you insights into what degree they effect performance. You can also cache views but it means there will be a lag on content updates being shown by the view.

In general you will also find more modules you add to drupal will have a performance impact although it could be slight. Even adding views to pages will add js and css and thus the more page weight so it will take longer to download. Also views run will have more db queries and have a performance impact on the database.

Was there something in particular you were looking for?
> 3 votes

---
Tags: 7, views, performance
---


title: Guestbook Title

text:
# Question
Title: Guestbook Title
I have installed the guestbook module but want to change the tab as displayed in the user profile and the text in the link so that they read 'User Feedback' rather than 'User Guestbook' and 'add feedback' rather than 'add guestbook entry'

Looked everywhere but can't find where to change the field label

Any pointers would be most appreciated.

# Answer
> 2 votes
string overrides works in almost every case ;), but there might be a nicer method, like hooking some methods of the gb module.

---
Tags: 7, string-overrides
---


# Question
Title: user warning: INSERT command denied to user
I am not able to insert rows into a table even though I have granted permissions to the corresponding database user.

I am able to insert rows into the same table with the same user from an individual php application. But if I try to insert a row from drupal, I get the error message as follows.

```
user warning: INSERT command denied to user 'username'@'localhost' for table 'table_name'

```

I even tried changing the password of the database user and changed the settings.php of drupal to reflect the new password, but still I get the same error message. I am able to run the `SELECT` queries successfully but not `INSERT` queries. What might be the problem here? Any help is appreciated. Thanks.

# Answer
That doesn't really make sense. Drupal is just a PHP application; if you're using **exactly** the same connection details in Drupal as you are in your stand-alone PHP application, and that works, it's only logical that your Drupal connection will work too.

You've obviously checked that the username and password are correct, but have you checked the Drupal is connecting to the server from `localhost`? That would be the only other possible difference. If Drupal is connecting from a remote machine then you'll need to grant specific privileges to the user for that specific location.

The easiest way to see what you've already got is to run a `SHOW GRANTS` query on the database in question. That will show you something like this:

```
Grants for username@localhost
GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, RELOAD, SHUTDOWN, PROCESS, FILE, REFERENCES, INDEX, ALTER, SHOW DATABASES, SUPER, EXECUTE, REPLICATION SLAVE, REPLICATION CLIENT, CREATE VIEW, SHOW VIEW, CREATE ROUTINE, ALTER ROUTINE, CREATE USER, EVENT, TRIGGER ON *.* TO 'username'@'localhost' IDENTIFIED BY PASSWORD '*xxxxxxxxxxxxx'

```

Plus a few more more rows more than likely.

Check through those rows to make doubly sure that there is a grant for `INSERT` for the database user AND the location that the Drupal website is connecting from.

**EDIT**

You could maybe get around the error using `drupal_write_record()`:

```
$record = new stdClass;
$record->col1 = 'something';
$record->col2 = 'something';
$record->col3 = 'something';

drupal_write_record('table_name', $record);

```

But that really *shouldn't* make any difference
> 1 votes

---
Tags: 6, database
---


# Question
Title: How to customize a specific content type display?
I have a content type which has many fields. My problem is that all fields displays in rows like this picture:
How can I customize these fields? for example I want them to arrange like this one:
Also I want to change some font-size (in the red box in second pic). What should I do? thx.

# Answer
with the FieldUI, (enable in modules), you can place the fields, see here `/admin/structure/types`. with display suite you can even do it more sophisticated.

but in the end you want to have your own theme, or adjust the one your using for css etc.
> 6 votes

# Answer
It seems like CSS Floats can do the job for you. Take a look at CSS Floats and clearing floats .
> 0 votes

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


# Question
Title: Get profile ID after using commerce_customer_profile_save()
Anyone has any idea how to get the profile\_id after I created a new profile using commerce\_customer\_profile\_save() ?

Apparently this function does not return the new profile object and I don't think it's very safe just to select last inserted profile from the database :(

# Answer
> 3 votes
Stupid me, it's in the $profile object itself.

```
commerce_customer_profile_save($profile);
$profile->profile_id;

```

---
Tags: 7, commerce
---


# Question
Title: Drupal 6: How to create a special case for searches on a limited set of single symbols (such as @ and ! and " and : )?
For the system I'm creating pages for some symbols have special functions. I have pages/nodes with those symbols as their title. @ and ! especially at issue because they appear in two different contexts (entirely different meaning in each), so there's two pages for each of them '@ (context A)' and '@ (context B)'.

When a user uses the Drupal Search, and searches solely on '@', those nodes should be in the search results. So far, I'm getting 'You must include at least one positive keyword with 0 characters or more.' when searching on the symbols, even after reducing the required word length to zero (I forced cron to run after doing so).

Does Drupal 6 strip out all or some of the symbols from the search text?

After playing with this for a while it occurred to me that since there's very few of these the approach might be to simply create a special case for them in the search. Is there a hook I could intercept in a module to handle the special cases? What's the best approach here? :)

Added Information:

To clarify, 'context A' and 'context B' were merely made up examples. the real thing would look more like: '@ (primitive)' and '@ (prefix)'. A search on '@' should turn up both, since the site has no way of knowing which (prefix or primitive) the user needs to know about.

# Answer
> 1 votes
Taking a fresh look at the problem this morning, I took a stab at finding out how to create a module to solve it. I think the search terms are run through 'check\_plain', stripping it down to just text (no symbols).

Turns out that a module providing the hook\_search\_prepocess hook can override the text used by the indexer and the search. So I put together a module in which my hook does a replacement of '@' with 'atsign', which appears to solve the issue. Also means I can set the minimum word size back to '3', as long as my replacement text is 3 or more characters.

I now have a sites/all/modules/searchfix/searchfix.module file (and corresponding .info file), with the following function in it:

```
function searchfix_search_preprocess($text) {
    return str_replace("@", "atsign", $text);
}

```

---
Tags: 6, search
---


# Question
Title: Potentially cancel all other submit handlers after my own
I've unshifted my own submit handler to the #submit handler of a node form. I already have a validation handler, so I can't execute my cancelling submit handler there.

Maybe this makes more sense:

1. my validation
2. all other validation
3. my submit handler, which potentially kills the submit process to `form_state[rebuild] => TRUE` and try again
4. all other submit handlers

Is that possible? I can cancel submission if I put my submit logic in a validation, but that's too soon. It should only run when all validation passes.

# Answer
> 2 votes
Ensure that your implementation of hook\_form\_alter() is the last one to be called. Your implementation of hook\_form\_alter() can then unshift one validation function and push a second validation function. The second validation function would then have complete information about whether other validation functions objected to saving the node (by calling form\_get\_errors()).

You can ensure that your your implementation of hook\_form\_alter() is the last one to be called by implementing hook\_module\_implements\_alter()

---
Tags: forms
---


# Question
Title: How a module can override theme suggestion?
Basically it was How to tell Drupal to look for templates in module directory? but I'll reword it, as **I don't want to define a new theme** (reason was already given).

What I want to do: in my module I have a file `node--attach.tpl.php` which is a modifed version of `node.tpl.php`. Now I want that, if view\_mode = 'attach' then this file is used. Also, theme should be allowed to override it with its own node--attach.tpl.php in theme folder.

# Answer
> 2 votes
This code works for me:

```
function MYMODULE_theme_registry_alter(&$theme_registry) {
  $mod_path = drupal_get_path('module', 'MYMODULE');

  $theme_registry_copy = $theme_registry;       // munge on a copy
  _theme_process_registry($theme_registry_copy, 'phptemplate', 'theme_engine', 'pow', $mod_path);
  $theme_registry += array_diff_key($theme_registry_copy, $theme_registry);

  $hooks = array('node');
  foreach ($hooks as $h) {
    if (!isset($theme_registry[$h]['theme paths'])) {
      $theme_registry[$h]['theme paths'] = array();
    }
    _MYMODULE_insert_after_first_element($theme_registry[$h]['theme paths'], $mod_path);
  }
}

function _MYMODULE_insert_after_first_element(&$a, $element) {
  if(is_array($a)) {
    $first_element = array_shift($a);
    if ($first_element) {
      array_unshift($a, $first_element, $element);
    }
    else {
      array_unshift($a, $element);
    }
  }
}

function MYMODULE_preprocess_node(&$vars) {
  if ($vars['view_mode'] == 'attach') {
    $vars['theme_hook_suggestions'][] = 'node__attach';
  }
}

```

I know you've seen nearly that exact code before from looking at your other question, but there are a couple of changes from the code in the article. It should work after clearing the caches (just once!)

Using the above I added a file called `node--attach.tpl.php` to my module folder, cleared the caches again, and the output from that template file was shown for the node.

Then I added `node--attach.tpl.php` to my theme folder, cleared the caches again, and the output from the new template file was shown.

---
Tags: 7, theming
---


title: .install file not working properly

text:
# Question
Title: .install file not working properly
I am new to Drupal, and I am trying to write a module with an .install file which will create a database table. The table isn't being created (as seen from the error codes when I try to access it. It also doesn't show up in the Schema module listing) and I don't know what I did wrong. Can someone see if they can find the error?

This is the code:

```
function email_form_schema() {
  $schema['subscription_info'] = array(
    'description' => t('The base table for nodes.'),
    'fields' => array(
      'first' => array(
        'description' => t('The first name'),
        'type' => 'varchar',
        'not null' => TRUE,
        'default' => '',
      ),
      'last' => array(
        'description' => t('The last name'),
        'type' => 'varchar',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'default' => '',
      ),
      'email' => array(
        'description' => t('The email address'),
        'type' => 'varchar',
        'length' => 32,
        'not null' => TRUE,
        'default' => ''
      ),
      'phone' => array(
        'description' => t('The phone number.'),
        'type' => 'varchar',
        'length' => 10,
        'not null' => TRUE,
        'default' => '',
      )
     ),
    'primary key' => array('email'),
  );

  return $schema;
}

function email_form_install() {
  // Create my tables.
  drupal_install_schema('email_form');
}

function email_form_uninstall() {
  // Drop my tables.
  drupal_uninstall_schema('email_form');
}

```

Here's the error when I try to access it:

> user warning: Table 'drupal620x120318224310.subscription\_info' doesn't exist query: INSERT INTO subscription\_info (first, last, email, phone) VALUES ('','','','') in C:\EasyPHP-5.3.8.1\modules\drupal620x120318224310\sites\all\modules\email\_form\email\_form.module on line 123.

I was missing the `return $schema;` line (which I modified above), but it still doesn't work. In the schema module it lists the "subscription\_info" table as missing. What does this mean?

# Answer
If I had a penny for every time I've done this...

You've forgotten to `return $schema` from your `email_form_schema()` function.

You'll need to reinstall the module (not just disable then re-enable) for the changes to take effect.

There's also a problem with the "last" column. It's a "varchar" and you're using the "unsigned" property which isn't compatible with that type.

You also need to provide the "length" property for all of the "varchar" type columns, including "first" and "last".
> 2 votes

---
Tags: hooks, database
---


# Question
Title: use custom tokens on a webform email confirmation
I have written a custom module which defines some tokens. These tokens are used e.g. in Wysiwyg editor this way: `[mytype:closing_date]` (I have token\_filter module)

Is it posible to make these tokens available also in the Webform module, and specifically in the confirmation e-mail that is sent after filling the form?

I tried `%mytype[closing_date]` but didn't work.

# Answer
use also the token module, you'll find instructions in its documentation.

basically, you'll need to implement these two hooks:

```
function my_user_token_values($type, $object = NULL, $options = array()) {
  if ($type == 'user') {
    $user = $object;
    $tokens['name']      = $user->name;
    $tokens['mail']      = $user->mail;
    return $tokens;
  }
}

```

and

```
function my_user_token_list($type = 'all') {
  if ($type == 'user' || $type == 'all') {
    $tokens['user']['name']      = t("The user's name");
    $tokens['user']['mail']      = t("The user's email address");
    return $tokens;
  }
}

```
> 1 votes

---
Tags: 7, webforms, tokens
---


title: multi contextual filters

text:
# Question
Title: multi contextual filters
i have three taxonomy voc for my products. they terms go above 1000 so i am using contextual filters

sub category
brand
price

i want to create contextual filter blocks for these taxonomy
say u click sub category the url has to change to /sb/sub category term
and then u click any brand the url has to be /sb/sub category term/bb/brand term
and then u click price url has to be /sb/sub cate term/bb/brand term/pp/price term

and I should like to have filter block also and hide it once clicked on the voc term.

Very example of this type is in amazon where u filtered down to the product(left side filter blocks) http://www.amazon.com/b/ref=sa\_menu\_lapnet9?ie=UTF8&node=2956501011

can anyone please help me on this

# Answer
If you are using drupal 7, you can use seach\_api + facet\_api + views , Here is a screen cast explaining how to here and here is an example site : look at the right side bar

(note that this screen cast is old facet\_api can be used without Solr integration)

If you are using Drupal 6 & unsing Shared host solution is faceted\_search If you have a private host the better solution would be : apachesolr + views you can find out a tutorial : here
> 0 votes

---
Tags: views
---


# Question
Title: Form data not being entered into the SQL statement
I have created a form which is not entering the data I enter in the fields into the sql statement. I just got the error:

> user warning: Duplicate entry '' for key 'PRIMARY' query: INSERT INTO subscription\_info (first, last, email, phone) VALUES ('','','','') in C:\EasyPHP-5.3.8.1\modules\drupal620x120318224310\sites\all\modules\email\_form\email\_form.module on line 124.

Here is the code:

```
function email_form_my_form($form_state) {
  $form['info'] = array(
    '#type' => 'fieldset',
    '#title' => t('Personal Information'),
    '#collapsible' => TRUE,
    '#collapsed' => FALSE,
  );

  $form['info']['first'] = array(
    '#type' => 'textfield',
    '#title' => t('First name'),
    //'#default_value' => $form_state['values']['first'], // changed
    '#description' => "Please enter your first name.",
    '#size' => 20,
    '#maxlength' => 20,
   );

   $form['info']['last'] = array(
     '#type' => 'textfield',
     '#title' => t('Last name'),
     '#size' => 20,
     '#maxlength' => 20
     //'#default_value' => $form_state['values']['last'], // added
   );

   $form['info']['email'] = array(
     '#type' => 'textfield',
     '#title' => t('Email address'),
     '#size' => 30
   );

  $form['info']['phone'] = array(
    '#type' => 'textfield',
    '#title' => t('Phone Number'),
    '#description' => "Format: 555-555-5555",
    '#size' => 10,
    '#maxsize' => 10
  );

  $form['subscription'] = array(
    '#type' => 'fieldset',
    '#title' => t('Subscription Information'),
    '#collapsible' => TRUE,
    '#collapsed' => FALSE
  );

  $form['subscription']['content'] = array(
    '#type' => 'checkboxes',
    '#title' => t('Events'),
    '#description' => t('Please chose which events you would like to follow'),
    '#options' => array(
      'Baseball' => t('Baseball'),
      'Basketball' => t('Basketball'),
    ),
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Submit',
  );

  $form['clear'] = array(
    '#type' => 'submit',
    '#value' => 'Reset form',
    '#validate' => array('email_form_my_form_clear'),
  );

  return $form;
}

function email_form_my_form_submit($form, &$form_state) {
  //unset($form_state['storage']);
if (db_query("INSERT INTO {subscription_info} (first, last, email, phone) VALUES ('%s','%s','%s','%s')", $form_state['values']['info']['first'], $form_state['values']['info']['last'], $form_state['values']['info']['email'], $form_state['values']['info']['phone'])) {
      //$form_state['values']['subscription']['content'] use this later...
      drupal_set_message(t('The form has been submitted.'));
}
else {
      drupal_set_message(t('The form had an error in it.'));
    }
  }
}

```

# Answer
> 3 votes
Drupal flattens the form values array so the element set at `$form['info']['first']` will be available in `$form_state['values']['first']`.

If you want it to be available in `$form_state['values']['info']['first']` you need to set the `#tree` attribute on the parent element:

```
$form['info'] = array(
  '#type' => 'fieldset',
  '#title' => t('Personal Information'),
  '#collapsible' => TRUE,
  '#collapsed' => FALSE,
  '#tree' => TRUE
);

```

There's more info available on the `#tree and #parents` documentation page if you're interested.

The alternative is to change your `db_query()` call to use the "default" method:

```
db_query("INSERT INTO {subscription_info} (first, last, email, phone) VALUES ('%s','%s','%s','%s')",
  $form_state['values']['first'],
  $form_state['values']['last'],
  $form_state['values']['email'],
  $form_state['values']['phone']
);

```

---
Tags: forms
---


title: Multi website Subdomains Content Types

text:
# Question
Title: Multi website Subdomains Content Types
Is there a way to have a d7 multi-site build with the same database, header, footer, sidebar but when a sub-domain is called it will display a different content type.

# Answer
You will have to set up multi site with the domain access module and also domain content type
> 4 votes

---
Tags: nodes, multi-sites
---


# Question
Title: Drupal Coding D7 - Taxonomy - How do I establish the hierarchy and associated fields for taxonomy terms?
Reviewing the code in Taxonomy.module I determined the array to define a taxonomy terms as:

```
 'taxonomy_term' => array(
      'label' => t('Taxonomy term'),
      'controller class' => 'TaxonomyTermController',
      'base table' => 'taxonomy_term_data',
      'uri callback' => 'taxonomy_term_uri',
      'fieldable' => TRUE,
      'entity keys' => array(
        'id' => 'tid',
        'bundle' => 'vocabulary_machine_name',
        'label' => 'name',
      ),
      'bundle keys' => array(
        'bundle' => 'machine_name',
      ),
      'bundles' => array(),
      'view modes' => array(
        // @todo View mode for display as a field (when attached to nodes etc).
        'full' => array(
          'label' => t('Taxonomy term page'),
          'custom settings' => FALSE,

```

Assigning the correct info in the array and calling `taxonomy_save_term($term);` creates the term, but I have not unearthed the method or array fields necessary to define the hierarchy and attach data fields.

Are there additional array key/values to identify the parent/children and fields?

Are the fields attached to a term in a separate operation after the term is created?

What array keys are required to create the term?

# Answer
> 2 votes
A taxonomy term is an entity in Drupal 7 so adding field data is exactly the same as adding it to a node, e.g.

```
$term = new stdClass;
$term->name = 'Term Name';
$term->vid = $vocab_id;
$term->field_some_field[LANGUAGE_NONE][0]['value'] = 'A value';
taxonomy_term_save($term);

```

The hierarchy is handled separately to this, in the `taxonomy_term_save()` function. All you need to do is add the parent term ID (`tid`) to the `$term` object before you save it, like so:

```
$term->parent = $parent_tid;

```

For multiple parents you would pass an array instead:

```
$term->parent = array($parent_tid_1, $parent_tid_2);

```

# Answer
> 2 votes
Here is an example:

```
// create the Foo vocabulary
$vocabulary = new stdClass();
$vocabulary->name = "Foo Name";
$vocabulary->machine_name = "foo_vocab";
$vocabulary->description = "Foo Description";
taxonomy_vocabulary_save($vocabulary);
// annoyingly taxonomy_vocabulary_save doesn't return any information about the vocabulary
$voc_vid = db_query("SELECT v.vid FROM {taxonomy_vocabulary} v WHERE v.machine_name = 'foo_vocab'")->fetchField();
$terms = array(
  'bar',
  'bat',
);
foreach ($terms as $term_name) {
  $term = new stdClass();
  $term->vid = $voc_vid;
  $term->name = $term_name;
  taxonomy_term_save($term);
}

```

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


title: is db_insert secure?

text:
# Question
Title: is db_insert secure?
I'm using the Drupal 7 method **db\_insert**, to insert data into a custom table in the Drupal database. I've read that this is the prefered way, however I've walked through the code and doco and I can't see anywhere which parses the values, or tells me that these values are safe.

Some of the values are coming from the user so I need to check against SQL Injection attacks.

This is the example I was reading, where the Drupal 6 parses the values, and the drupal 7 version does not.

```
<?php
// Drupal 6 version
db_query('INSERT INTO {vchess_games}
   (gid, timestamps, white, black, state, board_white, board_black) ' . "VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s')",
   $gid, $timestamps, $game['white'], $game['black'], $state, $board_white, $board_black);

// Drupal 7 version
db_insert('vchess_games')
  ->fields(array(
    'gid' => $gid,
    'timestamps' => $timestamps,
    'white' => $game['white'],
    'black' => $game['black'],
    'state' => $state,
    'board_white' => $board_white,
    'board_black' => $board_black
  ))
  ->execute();
?>

```

# Answer
The Drupal database layer wraps around PDO and uses prepared statements, so yes, the insert statements are sanitised and protected from SQL injection attacks.

This quote from the Prepared Statements docs says it best:

> The parameters to prepared statements don't need to be quoted; the driver automatically handles this. If an application exclusively uses prepared statements, the developer can be sure that no SQL injection will occur (however, if other portions of the query are being built up with unescaped input, SQL injection is still possible).

The same is true for all of the database functions in Drupal 7 (`db_select`, `db_delete`, etc.). The only one that is still potentially insecure is `db_query()` which will execute any arbitrary string you pass to it. Even with `db_query()`, though, you can pass in parameters so your query is safe.

The Database abstraction layer docs have some more information.
> 13 votes

---
Tags: database, security
---


title: Best builtin way for footer generation

text:
# Question
Title: Best builtin way for footer generation
What would be the drupal 7 options to generate the footer links?

Writing the links by hand could lead to 404 errors if links change...

# Answer
It's fairly simple:

1. Create a menu at http://mysite.com/admin/structure/menu/add
2. Add some links to it
3. Go to http://mysite.com/admin/structure/block and assign the automatically generated block for your new menu to your theme's footer region.

If your theme doesn't have a footer region you can add one by adding a line like the following to the theme's `.info` file:

```
regions[footer] = Footer

```

And then edit `page.tpl.php` to add the new region wherever it sits best in your HTML:

```
<?php echo render($page['footer']); ?>

```
> 5 votes

# Answer
Clive's answer is great if you want a footer where admins define the footer links manually. I usually prefer auto-generated footers using various Views blocks (I find Views more flexible than anything specific to footers would be).

If you want a footer that automatically tracks an existing menu but presents it differently, look into one of the many modules that put menu data into views. I've had (so far) good experiences with Menu Node Views despite it not having a stable release yet.
> 1 votes

---
Tags: blocks
---


# Question
Title: Creating an Editor Role and Reusing the Admin Menu and Overlay in Drupal 7
I, like so many other Drupal users, wish to add an Editor role into my website. I have already done this. I want the Editor to be responsible for editing and publishing certain content, as well as create certain types of content.

I use the Admin Menu module so I get that very nice flyout-menu administrator toolbar. Well, I want the editor to be able to use the same menu, only with certain items missing. Not only do I want them to use the same menu, but I want it to appear in the same bar. I also want the editor to be able to use the overlay as well, just as it appears for the administrator.

How do I do this?

Cheers.

# Answer
Assuming you have the Administration menu module enabled, under People \> Permissions check the following boxes:

Administration menu

* Access administration menu

Node

* Bypass content access control (note though, this gives the user permission to delete all content; if you don't desire this then you can micro-manage the permission on the individual content types, it's more box checking but also more secure)

System

* Use the administration pages and help
* View the administrative theme

Those are the core permissions that you need to have in order for a role to view the administration menu as well as menu items pertinent to managing site content.

Now, in order to make sure that the role is more or less secure, I would always uncheck every box whose label begins with "Administer...", as these permissions would be for administration roles.
> 7 votes

# Answer
See the Administration Menu Source to achieve this.

> Use a different menu as the Administration Menu. Configurable per role.
> 1 votes

# Answer
See the Menu per Role module to achieve this. Here is a quote about it (from the module's project page):

> ... allows you to restrict access to menu items (\*) based on user roles. It depends on the Drupal core menu.module—just activate both modules and edit a menu item as usual. There will be a new fieldset that allows you to restrict access by role. The fieldset also appears in the node edit form.
>
> (\*): We wrote "menu items", not "nodes" ... This module does not prevent users from accessing the destination nodes. It only changes the visibility of the menu items.
> 0 votes

---
Tags: 7, users
---


# Question
Title: Best way to search and replace text from blocks
Is there a module or some other method to find and replace text from all existing blocks? I've come accross Search and Replace Scanner Module but it looks like it only does search and replace on nodes.

Much Thanks.

# Answer
> 1 votes
Are you referring to custom blocks, not those provided by modules? If so, the main data is in the `body` column of the `block_custom` table in MySQL.

You could use an SQL query to perform the replacement.

```
UPDATE `block_custom` SET `body` = replace(body,"findstring","replacestring");

```

---

Credit: ChrisBrunner.com

---
Tags: blocks
---


# Question
Title: How use bulk action (VBO) with table pagination?
I have a table result with *n* pages. I would like to be able to select checkboxes from several different pages of results and then execute a bulk operation. However, when I have selected a checkbox and go to the next page my previous choices are lost. How can I keep my choices saved across page loads?

# Answer
This is only supported in the Drupal 6 version of VBO (the option is called "Preserve selection across pages" and I think it's enabled by default). There's an open issue request for the Drupal 7 version: http://drupal.org/node/1207348 This is not a priority for me so I don't see it fixed in the next few months (unless someone else takes the lead).
> 1 votes

---
Tags: views
---


# Question
Title: Drush pm-update: How can I stop it from trying to update more recent dev releases?
I'm using drush 5 to update the modules on my site. Usually it works great. However, when I have downloaded a dev release, **even if there is no more recent point release** it tries to update the dev release module to the last official "point" release.

For example, I have heartbeat-dev installed (2012-Mar-20). Yet when I run the `drush up` command, it prompts me to update to heartbeat 1.0 (2011-Jun-25).

If there is a newer dev release, I want to update to that. If there is a newer point release, I want to update to that. But if I have a dev release and the point release is older, I don't want to update. How can I do this?

I've been handling this manually but as the number of modules on my site grows it's getting harder to keep track of which to update and which not to update...

# Answer
Basically, this sounds like a bug that should be addressed in the drush issue queue. I'm guessing this is recent; it used to be that Drush would never go from dev to stable unless you used pm-download. Now it is being a bit overzealous.

As a workaround, you can use the --lock option to stop Drush from updating the module at all (drush pm-update --lock=heartbeat), but this will also exclude newer dev releases as well.
> 5 votes

---
Tags: drush
---


title: Calling a block by AJAX

text:
# Question
Title: Calling a block by AJAX
I want to call a block on a page by AJAX. This is appearing in content and not in a block region.

\[Use case: I have a View listing countries and their details; I want to add, at the top of the View, the user's country. I want the page to be cached, hence using AJAX to call back a View Block\]

In the header of my view I have:

```
<div id="load-ajax"></div>
<script>
(function ($) {
  $('#load-ajax').load('/example/test');
}) (jQuery);
</script>

```

In hook\_menu I have

```
$items['example/test'] = array(
    'title' => 'AJAX Delivery Test',
    'page callback' => 'show_example_block',
    'delivery callback' => '_basic_print',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );

```

I then have two functions:

```
function _basic_print($page_callback_result){
  print $page_callback_result;
}

function show_example_block(){
  if (isset($_COOKIE['country'])){
    return views_embed_view('example', 'example_block', $_COOKIE['country']);
  }
}

```

This works fine, but I'm wondering whether I'm missing anything. Is there a simpler, slightly more native way of doing this?

# Answer
```
<?php
$block = module_invoke('module_name', 'block', 'view', 0);
print $block['content'];
?>

```

Try including the view block.
> 2 votes

---
Tags: 7, ajax
---


title: Content Profile tab

text:
# Question
Title: Content Profile tab
I am on Drupal 6, and I needed to implement "Content Profile".

We want the users to gain access to their "profile" in edit mode, so we will provide a link with the following pattern: /user/%/edit/. There, the users see the merged view (user/password + content profile).

The thing is setting the following options to "true":

* Redirect on User Edit page
* Disable the normal User Edit tab

I want to add an extra tab ("my favorites") on top of this page, so that user can access his "flagged" content.

I am banging my head on my keyboard since this morning: No tabs are displaying. I used `hook_menu_alter()`, added a view as shown here, but to no avail.

Do you have any ideas?

# Answer
You don't need to alter a menu if you want to add one. Use `hook_alter()`.

How do i use hook\_menu to add a menu item into an exisiting menu contains a lot of useful ideas to takle down not showing menus.
> 1 votes

# Answer
There are two modules that try to solve this problem, but I cannot tell you if they work as advertised. I recommend that you try it out on a test site first.
> 1 votes

# Answer
```
    <?php

// $Id: content_profile_edit.module,v 1.1.2.32 2009/09/23 11:56:50 Solide Exp $

/**
 * @file
 * Allows exposure and processing of content_profile node fields at user modification
 */

/**
 * Implementation of hook_form_alter().
 */

function content_profile_edit_form_alter(&$form, &$form_state, $form_id) {
    global $user;
  if (($form_id == 'user_profile_form') && ($user->uid != 1)) {
    require_once drupal_get_path('module', 'node') .'/node.pages.inc';

    // Allow other modules to customize the used profile types, so modules
    // can easily customize the modification form.
    $default_types = content_profile_get_types('names');
    $form += array('#content_profile_edit_use_types' => $default_types);
    foreach ($form['#content_profile_edit_use_types'] as $type => $typename) {
            //content_profile_edit_modify_profile_form($type, $form, $form_state);
            content_profile_edit_modify_profile_form($typename, $form, $form_state);
    }
    $form['#theme'][0] = 'user_profile_form';

  }
}

/**
 * Helper function to return all available fields for a particular content type.
 *
 * @param string $type
 *   The content type to return fields for.
 * @return array
 *   Associated fields for the given content type.
 */
function _content_profile_edit_get_fields($type) {
  $typeinfo = content_types($type);
  return $typeinfo['fields'];
}

/**
 * Returns an array of selectable form elements that may be hidden, mostly containing CCK fields.
 *
 * @param string $type
 *   A content type to get the select elements for.
 * @return Array
 *   An array of fields suitable for use in a select field.
*/
function _content_profile_edit_get_field_select($type) {
  $fields = module_exists('content') ? _content_profile_edit_get_fields($type) : array();
  $return = array();
  if (!module_exists('auto_nodetitle') || auto_nodetitle_get_setting($type) != AUTO_NODETITLE_ENABLED) {
    $return['title'] = t('Title');
  }
  foreach ($fields as $fieldname => $info) {
    if (!$info['required']) {
      $return[$fieldname] = drupal_ucfirst($info['widget']['label']);
    }
  }
  $return['other'] = t('Other form elements (except for required CCK fields)');

  return $return;
}

function content_profile_edit_modify_profile_form($type, &$form, &$form_state) {
  // Fetch profile node and add in its form.

  $node = content_profile_load($type, $form['#uid']);
  if (!$node)
    $node = array('uid' => $form['#uid'], 'type' => $type);

  // Get the original node form.
  $node_form = drupal_retrieve_form($type .'_node_form', $form_state, $node);
  drupal_prepare_form($type .'_node_form', $node_form, $form_state);
    //print_r($node_form);
  foreach($node_form as $key => $value) {
    if(in_array($key, array('#id', 'form_id', 'form_token', '#token', '#action', '#parameters', 'author'))) continue;
    if(in_array($key, array('#submit', '#validate'))) {
      $form[$key] = array_merge($form[$key], $value);
      continue;
    }
if(!in_array($key,array('uid'))){

   $form[$key] = $value;
   }
  }
   //$form_state['rebuild'] = true;
  //$form['author']['name']['#default_value'] = $form['account']['name']['#default_value'];
  //unset($form['uid']);
  //unset($form['name']);
  //unset($form['submit']);
 // unset($form['#submit']);
 //print_r($form);die;
  unset($form['#redirect']);
  $form['#submit'][] = 'content_profile_edit_user_modify_submit';
  $form['#validate'][] = 'content_profile_edit_user_modify_validate';
 //echo '<pre>';  print_r($form['#submit']);echo '</pre>';
  // Remove submit handler here, we only want it to be triggered on save, not on preview.
  // We will call it ourselves from our save handler.

  //$form['#submit'] = array_diff($form['#submit'], array('user_profile_form_submit'));
  //$form['#validate'] = array_diff($form['#validate'], array('user_profile_form_validate'));
  //$form['#theme'] = 'user_profile_edit';
  // Also remove node validation.  We will call node_validate ourselves from content_profile_edit_user_modify_validate()

  $form['#validate'] = array_diff($form['#validate'], array('node_form_validate'));
 // unset($form['#validate']);

}

/**
 * Validates the user edit form
 */
function content_profile_edit_user_modify_validate($form, &$form_state) {

//echo '<pre>';print_r($form_state);die;
 // echo $form_state['clicked_button']['#id'];die;
  // Make sure the language setting saves.
  if ($form_state['clicked_button']['#post']['language']) {
    $form_state['values']['language'] = $form_state['clicked_button']['#post']['language'];
  }

  user_profile_form_validate($form, $form_state);
  $node = $form['#node'];
  if($form_state['clicked_button']['#id'] === 'edit-submit'){
      $node = $node->_account;
  }
  require_once drupal_get_path('module', 'node') .'/node.pages.inc';
  $node->changed = strtotime(date("Y-m-d H:i:s"));
  unset($node->name);
  node_validate($node, $form);
}

/**
 * Submits the user edit form
 */
function content_profile_edit_user_modify_submit($form, &$form_state) {
/*echo '<pre>';
print_r($form_state);
die;*/
//echo '<pre>';print_r($form);die;
  if($form_state['clicked_button']['#id'] == 'edit-submit'){
        $node = $form['#node'];
    //echo '<pre>'; print_r($form_state['values']['_account']);die;
     // user_profile_form_submit($form, &$form_state);
      global $user;

    //  $node->uid = $user->uid;

      $node = node_submit($node, $form);
     // print_r($node);die;
      node_save($node, $form);
  }
}

```

make an info file yourself.
> 1 votes

---
Tags: users
---


# Question
Title: Display a field of one content type in another content type
I am using drupal 7.I have created two custom content types Bank details and Loan offers. Now in loan offers i want the logo of the bank to be displayed.The logo image is part of bank details content type.can it be done using node reference?I need help to resolve this issue.Thanks.

# Answer
> 4 votes
You have a choice of modules for this:

Any one of those modules will allow you to create a field on your Loan Offers content type that references a Bank node. Then you can use Views/custom code/etc. to display the bank's image on the loan offer's node pages.

---
Tags: entities
---


# Question
Title: Drupal 6: Feeds mapping node taxonomy term
I using feeds module for import data from xml to node.

I have XML:

```
<root>
<item>
<title>Example 1</title> <!-- map to node title-->
<body>Body of example 1</body> <!-- map to node title-->
<term_name>My_term</term_name>
<term_tid>15</term_tid>
</item>
</root>

```

```
SELECT tid, vid, name FROM term_data;
tid vid name
15  19  My_term

```

If I map `<term_name>` to my node taxonomy term (and term name exist) its working.
But If i map `<term_tid>` to my node taxonomy term (and term tid exist) it's **NOT** working. Why?

Thanks for helping

# Answer
> 0 votes
I solve for category\_tid:

```
function my_module_feeds_after_parse(FeedsImporter $importer, FeedsSource $source) {
if ($source != null && $source->id == 'import_my_module') {
  $vid = 19 //id of vocabulary
    foreach ($source->batch->items as & $item) {
      if (($category = db_fetch_object(db_query("SELECT tid, vid, name, description FROM {term_data} WHERE tid= %d AND vid = %d", $item['<term_tid>'], $vid))) !== FALSE) {
        $item['<term_tid>'] = new FeedsTermElement($category);
    }
  }
}

```

# Answer
> 0 votes
before importing nodes from a site that contains taxonomy terms , try first to import all taxonomy terms ( you can use taxonomy manager ).

Feeds will add a term with a new tid if It not exist , not the same as tid of the site from where you export

---
Tags: taxonomy-terms, feeds
---


title: Show a node (content) in a light box D7

text:
# Question
Title: Show a node (content) in a light box D7
I need to show a video in a light box on a site and am having difficulty. I thought I would create a normal page with the proper code but when I go to load the video the screen grays out then goes and loads the page but gets stuck as if it cannot do it. I also tried just creating an html file and loading it directly but it couldn't read it or failed or something. I am using fancy box and html 5 if that matters. How would I do this? If you need more info please let me know Thanks for any help guys

Edit: I have tried the solution below which is what i need it just isn't quite working yet. the url of the node is: http://fourcemag.com/homme/video and http://www.fourcemag.com/homme/video-0/video so the last part of the url is video

This is the code:

```
function fource_preprocess_page(&$vars) {
  $path = $_GET['q'];
  $path = drupal_get_path_alias($path, $path_language = '');
  $patharray = explode('/', $path);

  if ($patharray[2] == 'video') {
    $vars['template_files'][] = 'page--video';
  }
}

```

This is the error:

* page--video.tpl.php

not sure what is wrong here. Please help Same error as before

# Answer
You will likely want to define a custom page.tpl.php for use in the lightbox so it doesnt conflict with your normal site pages where you would like sidebar content etc.

Think of having 2 differently themed versions of the same page, your traditional page and a cut down version which is only the node content area.

To do this, add a theme\_preprocess\_page() so it creates a unique url argument to trigger the content only display via its own tpl.php:

```
function YOURTHEME_preprocess_page(&$vars) {
  // Get the path (eg node/#) and split it into an array ([node][#][video])
  $path = $_GET['q'];
  $path = drupal_get_path_alias($path, $path_language = '');
  $patharray = explode('/', $path);

  // If the last part of the path is "frame" use the page-content.tpl.php
  if ($patharray[2] == 'video') {
    $vars['template_files'][] = 'page--video';
  }
}

```

Then copy your exiting page.tpl.php into a page--video.tpl.php and trim out all the content you dont wish to see in your lightbox.

EDIT: (include details on using the video only page) In your iframe load your node page with "video" appended to the drupal url. For example **"node/135/video"** so it using the **page--video.tpl.php**

I have been using this solution to embed content from our nodes into another application and it works well. :)
> 2 votes

# Answer
I need also in a site to display a page as a pop up in a shadow box,I used a colorbox module because it give me option to open iframe (I don't know if light box can do it or not but I think color box is similar to light box) and I override the page.tpl.php to my page to remove all region except my content
> 1 votes

---
Tags: 7, nodes, javascript
---


# Question
Title: Is there a (suite of) module(s) that handles custom event occurrences e.g. "last Sunday every month, except in August", linking content and users
I'm either looking for or considering writing an event calendar module that can handle custom occurrences. For example:

* Last Sunday of every month
* Last Sunday of every month except August
* Second and Fourth Tuesday of every month
* Every other Saturday, until May
* A particular date each year
* Several particular dates each year

... as well as more uniform, simpler events

I would want the logic of such occurrences to be built in and centralised in an event configurer interface as much as possible, rather than have independent copies made of each event (e.g. 10 copies of an occurence populate in the calendar). Reason being is that the event occurrences can be adjusted in one place and the changes are immediate on all occurences.

Background: I used to run a community radio station site based on Drupal and had a need then for publicising community group events with these kind of fairly complex frequency.

I would like to use the system for other purposes like arts events.

I'd also like to link users and resources, e.g. to send out reminders and perhaps provide functionality like Outlook calendaring, even perhaps for booking equipment and resources.

I've looked at events modules on Drupal but not sure if there is one that quite meets these requirements.

I would be willing to consider writing one if not already implemented.

# Answer
**Updated 2014 01 03**

The Date field offers much of this functionality listed in the bullets and there are add-on modules like Date Repeat Instance that make it easier to add exceptions.

~~**(Updated)** following feedback~~

~~Looks like there isn't a (suite of) module(s) that quite match my needs. So I'm going to consider embarking on writing a suite of modules, perhaps this might break down into:<br>~~ ~~* A module for the logic of handling the occurences and an API
* A UI module for providing the user the ability to setup the occurences
* A module that provides some supporting libraries, including exposure via Views~~* ~~various modules that provide applications of the above~~
> 0 votes

# Answer
You can take a look at opening hours module. It's not exactly what you're after and depending on what/how you're building this might not work for you, but it can allow you to setup data selection with repeat occurrences that can be overwritten. It might help you out on figuring out how to create what you're after yourself, since the UI is pretty close you what you're after.
> 1 votes

---
Tags: 7, datetime
---


# Question
Title: Remove RSS feed icon and create custom RSS feed
1. I want to disable the default Drupal 7 RSS feeds located at /rss.xml. Can this be achieved?
2. I want to create my own custom RSS feeds. I have tried with the Views module, but I can't define my own fields, and default feed contains a lot of HTML etc. I just want to create a clean RSS feed with title and body summarized to 150 chars, but without HTML, like in this feed: b.dk/seneste/rss.

# Answer
> 3 votes
For your first question, I found the RSS Permissions module, which allow you to disable the RSS feeds based on roles. I haven't tested this out, but it seems to be actively developed. (NOTE: This is for Drupal 7.)

# Answer
> 1 votes
For question 1, I have used the answer by Rick Umali.

For question 2: I made a field formatter for the text fields called "Trimmed and stripped" that first strips all HTML and then trims the length of the value. Next I configured the RSS display type for my content types to use this "Trimmed and stripped" field formatter on body. Finally I created the wanted views through Views 3.x module.

But this still leaves HTML around each field. And I wanted to have a clean RSS feed, so I also created a template file named views-view-row-rss.tpl.php, which runs a htmlspecialchars\_decode() on $description, and then strip\_tags() and finally check\_plain()...

And I now got the wanted result - but I think there most be a better solution out there... Or else I should maybe write a module for this one day :)

# Answer
> 0 votes
Question 1: You should use Views module to create a feed on that path, this will override the items included in the home page feed.

Question 2: You can change the default RSS settings for the site to include full node content or the title or title + summary. Then on a per content type you can set a custom display for feeds, if you need to tweak what is included in the feeds.

---
Tags: 7, feeds
---


# Question
Title: Expiration of cached pages stuck at 6 hours
No matter what I change in the GUI, after clicking save the `Expiration of cached pages` under Performance options is reset to 6 hours. I checked my default VCL for Varnish suspecting this might be something set there, but couldn't find a 6 (hours) or value of 21600 (6 hours in seconds) there.

I'm pretty new to Varnish so not sure if it might be some default value, or what that could be called (or if Varnish is the culprit here at all, just a hunch).

We need to have Varnish keeping pages cached indefinately by default, and caches to only get cleared when content updates.

# Answer
The settings.php file contained the following line, which caused the behavior I was observing.

```
$conf['page_cache_maximum_age'] = 21600;

```
> 1 votes

---
Tags: caching, proxies
---


title: after_update doesn't fire

text:
# Question
Title: after_update doesn't fire
I don't know what the problem is, but why don't after\_update fire? I can replace it with insert and it works but this doesn't for some reason.

```
function maillist_user($op, &$edit, &$account, $category = NULL){
    if($op == 'after_update'){
        maillist_register_submit();
    }
}

```

What I am trying to do is as soon as a new user is registered to my site I want to use that uid but I can't figure out how to get that uid.

# Answer
> 1 votes
The **after\_update** case called is called after the user modifies his account from my understanding of hook\_user.

So that would mean that the user account has been created and the user updates his profile such as changing user image or password etc., which would trigger **update** and `after_update`.

I guess when the user is created it is only normal that the insert is triggered. If you have customized the registration so that in course of the registration the user account has been created and while completion the account information is being modified by him the update and after\_update would be triggered.

If you wish to get the uid of the user who's registered most recently I suggest you could implement `hook_user` with insert case and query the database to get the max(uid) which would be the recently added user's id, only making sure your module has a greater weight so that user module's insert of the user happens first and your retrieval of the uid follows it. Though my suggestion feels less than optimal I believe it would work.

---
Tags: 6, hooks
---


# Question
Title: How do you troubleshoot search tracking not working with the Google Analytics module?
I have a site that uses the Google Analytics module. Analytics is working fine. However, I enabled search tracking in the module -- and updated the query string to search in GA -- but search data is not being tracked. After 72 hours I'm not seeing any search data.

I'm unsure how I can troubleshoot this. I reviewed the JS routine being output on the search page and verified the GA code is appearing, though I don't see anything specifically relating to search (not sure it would output anything different).

How do I go about troubleshooting this?

# Answer
> 1 votes
You could try the GA debug chrome extension for troubleshooting this issue. It will give you better insight into what is being sent to GA from Drupal

---
Tags: 6, search, google-analytics
---


# Question
Title: in hook_preprocess_node, how to tell if node is being edited?
In hook\_preprocess\_node (or other themable hook), what is the easiest way to tell if node is being edited? I would like to add some javascript only when viewing the node, not editing.

# Answer
> 3 votes
`hook_preprocess_node()` doesn't get fired for node edit pages so you don't need to do any checks, you can just add your JS as normal.

---
Tags: 7, nodes, hooks
---


# Question
Title: Dynamically fetch feeds and html content from other website and show
Is there any module that pulls data from external feed or html link and displays in drupal. It should not create any corresponding nodes in drupal. It should just go and scrape data or feed and display in a page or block.

# Answer
> 1 votes
Feeds is the way to go. It includes an HTML parser and can fetch data from existing URLs.

Here are some links to parsers for Feeds that can suit your needs.

# Answer
> 0 votes
Activate the Aggregator Module which comes with Drupal. This allows you to fetch feeds and display them as blocks or use them in views and so on.

# Answer
> -1 votes
Not Aggregator Module alone, you need Aggregation also. Here is a quote about it (from the module's project page):

> ... aggregates content from XML feeds. RSS 2.0, ATOM 1.0 & RDF 1.0 are supported, but its architecture is easily expandable to support any XML format, check out the README file for details. Following are some of its features :
>
> * Highly efficient. This module was created for performance.
> * Ability to assign term(s) to all items generated from a feed.
> * Ability to dynamically tag all incoming items during feed handling phase. For example, RSS, ATOM & RDF categories are automatically extracted, added as terms, and auto-attached to aggregated items.
> * Integrates with OG. If the feed is set as a group, all items are assigned as posts under it (parent-\>child). If the feed is set as a post, all items are assigned as posts under the feed's group (siblings).
> * Built-in support for handling feeds that require HTTP authentication.
> * Built-in support for handling feeds that require FTP authentication.

---
Tags: 7
---


title: Creating a node using Services 6.3 REST

text:
# Question
Title: Creating a node using Services 6.3 REST
I am trying to create a node using the rest service. I am hitting `/myendpoint/node` using a post. My header is `application/json`. I am not sure what I need to post as the data.

# Answer
Something along the lines of this, &node\[title\]=testnode&node\[type\]=story&node\[field\_test\]\[0\]\[value\]=testtting

Also, if you are ever unaware of what to send, just look at the tests.
> 1 votes

# Answer
This might give you some ideas: https://gist.github.com/affc9864487bb1b9c918.

I assume you have `Content-Type: application/json` in your header.

Example curl call with session authentication:

```
curl -X POST "http://example.com/endpoint/node" -H "Content-Type: application/json" -H "Accept: application/json" -H "Cookie: {session_name}={session_id}" -d '{"type":"story","title":"Test Title","body":"Test Body"}'

```

Basically you have to post data in JSON format, that maps to the fields of the content type you want to create. If you have custom fields it is just a bit more tricky. See: http://drupal.org/node/1354202.
> 1 votes

---
Tags: nodes, 6, services
---


# Question
Title: Slow query with large dataset in Drupal views — better to process in SQL or PHP?
I have a large userbase in my Drupal 7 site, which contains a People finder. Because there are hundreds of thousands of users and we want to display the People finder in a random order on page load, I presume it's transferring the whole userbase into memory at some point, in order to paginate (using the Pager built-in to ~~Views2~~ Views3).

I've noticed that the query has no `limit` against it (presumably because of pagination) and that it `join`s against `users_roles` twice (because I need to include all users of rôle A but not also of rôles B, C and D). I've added comments against the `WHERE` clause to explain each line's purpose and how it's come out of my View.

```
SELECT
    users.uid AS uid,
    'user' AS field_data_field_user_image_user_entity_type,
    'user' AS field_data_field_user_field1_user_entity_type,         -- custom field
    'user' AS field_data_field_user_field2_display_user_entity_type, -- custom field
    'user' AS field_data_field_user_field3_user_entity_type,         -- custom field
    'user' AS field_data_field_user_field4_user_entity_type,         -- custom field
    RAND() AS random_field
FROM
    users users
    INNER JOIN users_roles users_roles ON users.uid = users_roles.uid
    LEFT JOIN users_roles users_roles2
        ON users.uid = users_roles2.uid
        AND (users_roles2.rid = :views_join_condition_0
          OR users_roles2.rid = :views_join_condition_1
          OR users_roles2.rid = :views_join_condition_2)
WHERE
    (( (users.status <> :db_condition_placeholder_3)      -- Active users only
    AND (users_roles.rid = :db_condition_placeholder_4)   -- Must be in rôle A
    AND (users_roles2.rid IS NULL)                        -- Must not be in rôles B, C, D
    AND (users.uid != :users_uid OR users.uid IS NULL) )) -- Must not be current user
ORDER BY random_field ASC

```

So I have two questions:

1. Is there some way in Views2 that I can somehow get this query to be `limit`ed (potentially by sorting on something else that pretends to be random)? I assume that transferring fewer result rows per query is likely to help with the memory overhead?
2. If I want to mess with that `WHERE` clause, am I better off using a PHP Filter Criterion to do the roles messing (which would presumably remove the double-join) or should I move the whole damn query into either a custom module\[a\] or a mySQL view\[b\]?

a: I assume that would attach to the relevant hook with a `function modulename_views_pre_execute(&$view)`.
b: I assume a mySQL view would still need to do both `join`s, one `inner join` and one `left join`, so I can't quite see how this would help.

For what it's worth, I know that my site will have a relatively short lifetime and, during that, the rôles won't change, so I am happy to hardcode the rôle IDs, if that will give me a performance benefit.

# Answer
Are you 100% positive that the view isn't paging in SQL? When you turn on Query Logging in the Devel module, what do you see for your view? I just double checked a site and am seeing (formatting is mine):

```
SELECT node.nid AS nid, RAND() AS random_field
FROM node node
WHERE (( (node.status = :db_condition_placeholder_0)
  AND (node.type IN (:db_condition_placeholder_1)) ))
ORDER BY random_field ASC LIMIT 10 OFFSET 0

```

when I am on paged view with a random sort.

I have seen the double `JOIN` thing before. Often, you can adjust the view parameters and get the query to run the way you want.

Optimizing these queries is really use dependent. I am pretty sure that both of the columns you are joining on are both indexed already. You can try to replicate the query manually, and then `EXPLAIN` it, and manually improve it. You can then implement this query in a custom block, but then you lose out on other things that Views give you. Caching the view results, may help, too.

Keeping everything in MySQL is likely best (it is meant for heavy lifting like this), but only profiling will give the true results for your system. Just make sure you have MySQL, Apache, and PHP tuned so that you aren't chasing the wrong problem.
> 2 votes

# Answer
You can easily modify the query in hook\_views\_query\_alter, add your `LIMIT` clause and see what you get.

But MPD advice above is very sound and is widely applicable.
> 1 votes

---
Tags: 7, views, performance
---


# Question
Title: How to decide in hook_nodeapi() if it was invoked after creating/updating node via Services module?
I am developing a custom module, which should do things in hook\_nodeapi() only if the node is being created/edited via Services. I couldn't find any data that is available at this point for deciding if the node is via Services or not.

I am aware of a possible solution, using `request_uri()` and deciding based on that (https://drupal.stackexchange.com/a/8568/1930), but it seems so wrong. Hardcoding the endpoint name is plain wrong. Workaround this by providing an admin interface and depend on configuration?

So, I would rather avoid the above, but couldn't come up with anything else so far. I am curious if others have had similar problems before and if there is a better solution.

UPDATE

The accepted answer should be used, as that is the cleanest solution. Unfortunately, I had to use a different one, which might still be useful to others so I am sharing it here: https://gist.github.com/Temaruk/5884209

# Answer
I think there's a point in the system not normally telling you this, since we want to avoid any kind of coupling between the systems. Based on that I guess there's no built in way to get the information you want. Strictly speaking, you should probably consider why you are doing what you are doing, as it's not good practice.

Possible methods: You could implement a custom node resource, which hands over node creation to the regular services callback after having done

```
$node->creator = 'services';

```

or possibly:

```
$node_origin = &drupal_static('node_creation_tracker');
$node_origin = 'services';

```

after which you could retrieve this data with the same method. Implementing a resource is not a complicated process, but requires quite a bit of knowledge about services.
> 3 votes

# Answer
You might be able to do something with user roles, eg, have all "real" people assigned a role in addition to just "authenticated user" and then check for that inside of nodeapi() (and then set a field inside the content to reflect that if you need this to have some permanence)
> 1 votes

---
Tags: 6, services, nodes
---


# Question
Title: How to get the content type in the zone/region tpl files?
How would I get the node type from within a zone/region or section (using omega theme) template file. I know how to override templates at the page/node level for specific content types - but I can't seem to find a variable or anything that points to what type of single, node page content type is currently being displayed.

# Answer
> 1 votes
If you are visiting some node then `arg(1)` call would return node id.

```
$nid = arg(1);
$node = node_load($nid);
$node->type

```

# Answer
> 1 votes
In your subtheme preprocess template, create a zone or region preprocess file. Let's do an example for region, where you would create the file (example for Omega 3 theme):

{your subtheme directory}/preprocess/preprocess-region.inc

In that file, create your preprocess function that gets the node and adds type to $vars.

```
<?php
function {theme_name}_alpha_preprocess_region(&$vars) {
  // get the node
  $menu_object = menu_get_object();
  if (isset($menu_object->type)) {
    $vars['node_type'] = $menu_object->type;
  }
}
?>

```

{theme\_name} would be the name of your subtheme. At this point, you can access the variable node\_type in your region--content.tpl.php file.

---
Tags: theming
---


title: is it possible to index a hidden field?

text:
# Question
Title: is it possible to index a hidden field?
i have a newsletter content type which consists of a link to a file (pdf) and a summary field. the idea behind the summary field is that it will contain a list of keywords and when a search hits one of these keywords the newsletter item (and so the pdf file) will be highlighted.

the issue is that i don't really want the summary text to be displayed, but if i set it as hidden in the display it doesn't seem to be indexed.

anyway that i can persuade drupal to index this field?

using 7.12 by the way if that's important.

Dave

# Answer
The best way should be implementing the search\_api module , with this module you can index anything and set the importance of the indexed field .

Here is a screen cast that shows how to implement here

Note that the screencast must be updated because facet\_api works now without apachesolr

Enjoy!
> 4 votes

# Answer
I think displaying the field and hiding it with css should do the trick.
> 1 votes

---
Tags: search
---


title: Openlayers Views map with auto render?

text:
# Question
Title: Openlayers Views map with auto render?
I have an openlayers map view that is populated with user IP address. I need the map to update automatically (without refreshing) when a new users visits the site.

Much like the behavior of the map on http://drupal.org/ i.e markers would appear but stay on map.

If anyone can point me into the right direction it would be much appreciated.

Thanks in advance!

# Answer
> 1 votes
For reference, here is a description on how the map on the D.O homepage was built. https://association.drupal.org/node/784

To achieve what you want, you could use the Views Auto-refresh submodule of the Views Hacks module to auto refresh the openlayers map view in short intervals.

---
Tags: views, theming, javascript
---


# Question
Title: File upload ajax and Radio Buttons not cooperating in registration form
I have enabled Profile 2 and profile Profile2 Registration Path modules on my site and have a really long registration form with lots of fields. I have some radio boxes and file upload fields also. The problem is when I upload a file without having selected a valid option for my mandatory radio box. IF the radio box is empty when I hit upload, the file gets uploaded and I get the error "illegal option, contact admin". After that the error keeps repeating if I try to remove the file.

In my reports I see

> Location http://localhost:6600/sitename/el/file/ajax/profile\_customer/field\_cv/und/0/form-Q8VxLye65S3tYFkcHSwO9Z58dG7Mhv6jRWRBnIst46s
>
> Referrer http://localhost:6600/sitename/el/customer/register
>
> Message Illegal choice in Specialty element.

The Specialty element is my radio box. If I enter an option in the radio box before uploading the document everything works as it should! Removing the file is troublefree also. I am completely baffled with this. I’ve searched and found many issues with file upload and radio boxes values connected to ajax. Seems weird that this thing isn't working. Can't be the only one with files and radio boxes in his registration form! Any ideas/pointers on how to solve this irritating issue?

# Answer
If I understand you right you'll need to write a small custom module to hook into the registration form using `hook_form_alter()`, and add the `#limit_validation_errors` property to the correct radio group. This should stop the validation from running on AJAX calls, but still let it run when the form is submitted.

The code might look something like this:

```
function MYMODULE_form_user_register_form_alter(&$form, &$form_state, $form_id) {
  $form['radio_button']['#limit_validation_errors'] = array();
}

```

It's quite likely that the particular radio group you're after will be buried in the nested `$form` array somewhere so you'll probably need to use the `dpm()` function (part of of the Devel module) to inspect the form and determine the correct element to alter.
> 0 votes

---
Tags: ajax, users, files
---


# Question
Title: Add data to JSON generated by views_datasource
I'm using "views datasource" to output a view as JSON - for each views row it's creating a JSON object with the fields as string/value pairs - all those objects are in an array which is the value to a string specified by the "Root object name" in the view's format settings. It looks like this:

```
{
  "nodes":[
    {
      "nodeid":"1",
      "title":"foo"
    },
    {
      "nodeid":"2",
      "title":"bar"
    }
  ]
}

```

Now I need to add another string/value pair to the main JSON object so it looks like this:

```
{
  "nodes":[
    {
      "nodeid":"1",
      "title":"foo"
    },
    {
      "nodeid":"2",
      "title":"bar"
    }
  ],
  "total_nodes":"2",
  "some_other_stuff":"here"
}

```

In another question I found out how I could add elements to the view's results but now I need to add elements "next to" the view's results. I just don't know where I need to put my code. Can anyone point me to a hook that would do the trick?

# Answer
> 3 votes
You could implement something in the view template for the JSON display.

The correct file to modify seems to be views-views-json-style-simple.tpl.php.

You have to copy it to your theme's template folder (usually template's root directory, or `template` subdirectory) and add the necessary data to the `$json` variable before the correct `print $json` statement.

---
Tags: 7
---


# Question
Title: Trouble theming Ubercart's cart page (Drupal 7) using hook_theme
Ubercart's **uc\_cart** module offers a 'cart' page which I'm willing to have a theme/template. What I did is added following in `mymodule_theme()`:

```
    'uc_cart_view' => array(
        'render element' => 'page', // IS THIS CORRECT?
        'template' => 'cart', // Located in mymodule/templates/cart.tpl.php
        'path' => drupal_get_path('module', 'mymodule') . '/templates',
    ),

```

But No luck!

**My Question:**

Shall I have some other value for `render element` key? Or shall I have a `variables` entry? I tried with `variables` with an empty array instead of `render element` entry but no luck.

Here goes some more information about Ubercart's uc\_cart module so that you can help me solving this issue:

**For Your Consideration**

Portion from `uc_cart_menu`:

```
$items['cart'] = array(
    'title' => 'Shopping cart',
    'description' => 'View/modify the contents of your shopping cart or proceed to checkout.',
    'page callback' => 'uc_cart_view',
    'access arguments' => array('access content'),
    'file' => 'uc_cart.pages.inc',
  );

```

So I figured out I should use my custom template for `uc_cart_view`. This `uc_cart_view()` is a function in \*uc\_cart.pages.inc\* page, I've pasted the function here for your convenience.

Any help on what I'm doing wrong?

# Answer
> 1 votes
uc\_cart\_view() is not a form builder; it is a page callback. As such, `theme_uc_cart_view()` is not automatically called for `uc_cart_view()`. It is the page callback that needs to call the necessary theme function, or refer it such as in the following code.

```
  if (empty($items)) {
    return array(
      '#theme' => 'uc_empty_cart',
    );
  }

```

What you can do is the following:

* Implement hook\_menu\_alter() to alter the page callback invoked for http://example.com/cart.

```
function mymodule_menu_alter(&$items) {
  if (isset($items['cart'])) {
    $items['cart']['page callback'] = 'mymodule_cart_view';
  }
}

```
* Implement the page callback to output the content as you want it to be.

I cannot suggest the code to write for `mymodule_cart_view()`. Looking at the code used from `uc_cart_view()`, I notice the main part is the following one.

```
  // Load the array of shopping cart items.
  $items = uc_cart_get_contents();

  // Display the empty cart page if there are no items in the cart.
  if (empty($items)) {
    return array(
      '#theme' => 'uc_empty_cart',
    );
  }

  $build = array();
  // Load through the cart panes...
  foreach (uc_cart_cart_pane_list($items) as $id => $pane) {
    // If the pane is enabled...
    if ($pane['enabled']) {
      // Add its output to the cart view.
      $build[$id] = $pane['body'];
    }
  }

```

What a page callback can return, in Drupal 7 is:

* a string containing the markup to output
* an array accepted from drupal\_render(), such as the following ones

```
$build = array(
  '#theme' => 'node',
  '#node' => $node,
  '#view_mode' => $view_mode,
  '#language' => $langcode,
);

```

```
$block = array(
  '#markup' => '<em>' . t('There are no rows matching the selected criteria') . '</em>'.
);

```

```
$styles = array(
  '#type' => 'styles',
  '#items' => $css,
);

```

As side note, in your theme definition, the template filename cannot be "cart"; as the template file is for "uc\_cart\_view" you can report it to be "uc\_cart\_view" or "uc-cart-view." Any other filenames are not accepted, from Drupal.

# Answer
> 0 votes
```
$items['uc_cart_view_form'] = array(
    'template' => 'cart/uc-cart-view-form',
    'arguments' => array('form' => NULL),
 );

```

Means you should use `uc_cart_view_form`

---
Tags: 7, hooks, theming, ubercart
---


# Question
Title: Tracking Sessions and Calling a web service
I have a module that simply has a couple functions that retrieve cookie information, set cookie information and calls a web service using the web service client to help track the users information. However, when i installed the module, it did not recognize the function that executes the loading of the service from the web service client. It returned the following error:

```
Call to undefined function wsclient_service_load()

```

The code is simple and looks like this:

```
function set_session_tracking_data() {
$sessionGuid = com_create_guid();

//Time for Cookie Experation
$time = time()+3600;

if (isset($_COOKIE["Drupal_VisitorGUID"])) {
    $sessionId = $_COOKIE["Drupal_VisitorGUID"];
}
else {
    $sessionId = $sessionGuid;

    setcookie('Drupal_VisitorGUID', $sessionId, $time);

    $params = array('visitorGuid' => $sessionGuid);
    $service = wsclient_service_load('tracking');
    $result = $service->CreateVisitor($params);
}
}

```

The function set\_session\_tracking\_data is being called from a module created solely for tracking purposes. It has no hooks. Simply has a function called set\_tracking\_params() and in that function we call set\_session\_tracking\_data(). The code is below:

```
function set_tracking_params() {
//Sets Module Path
$modulePath = drupal_get_path('module', 'eddy_tracking');

//Time for Cookie Experation
$time = time()+3600;

if (!isset($_COOKIE["cid"]) && !empty($_GET['cid'])) {
    setcookie('cid', $_GET['cid'], $time);
    dsm($_COOKIE["tsource"]);
}

if (isset($_COOKIE["key"]) && empty($_GET['key'])) {
    setcookie('key', $_GET['key'], $time);
}

set_tracking_params()
}
set_eddy_tracking_params();

```

I made the wsclient a dependency but it still does not recognize the function. If i put this same code within a block module i created, the code executes without a hitch. Can someone please help me with this issue? Or perhaps someone can mention to me the best practice at setting sessions and tracking a users session. Any help would be greatly aprreciated. Thanks!

# Answer
> 2 votes
There seems to be a bit of confusion in your code: the `set_tracking_params()` function calls itself, which would would result in an infinite recursion.

That being said, you're calling the `set_eddy_tracking_params ()` function directly in the PHP file which means it will probably be executed before Drupal's full bootstrap has run, and before the wsclient module file has been loaded.

If you're trying to run this function on every page then `hook_init()` would be the best place for it; it's called early on in every page load:

```
function MODULENAME_init() {
  set_eddy_tracking_params();
}

```

---
Tags: sessions, services
---


# Question
Title: FAPI redirect *and* store to local database
**What I'm trying to achieve**

I am successfully using the Form API in Drupal 7 to dynamically alter Webforms to redirect to an off-site URL on submit.

What I need is twofold; I need (a) for the client to visit the offsite URL so the site can store a lead via query string parameters, as well as (b) for the same information to be documented in my local Drupal database.

*Every lead must be documented*, so I have tentatively ruled out JavaScript/AJAX as an option.

**How I tried it**

I thought the best way to do this was to set up a module with `$form_state['redirect']`:

```
/**
 * Implement hook_form_alter to change the form's submit action
 */
function myform_form_alter(&$form, &$form_state, $form_id) {
    $form['actions']['submit']['#submit'][]='myform_submit';
}

/**
 * Callback as specified above
 */
function myform_submit($form, &$form_state) {
    // Values for the query string
    $vals = array('mykey' => 'myval');

    // Redirect appropriately
    $form_state['redirect'] = array(
        // $path
        'http://www.anotherwebsite.com/',
        // $options
        array('query' => $vals),
        // $http_response_code
        302,
    );
}

```

I did that, and as expected, the user is redirected immediately after form submission. However, the Form API does not *submit to my database* before redirecting the user.

I read the FAPI documentation for Drupal 7. I sought using `#action`, although it apparently reports only accepting internal values and my users must visit an offsite URL. I wound up using `redirect` in the meantime, which was no longer documented but was suggested in the comments.

Where do I go from here?

**EDIT: tenken's response works, but I have another problem!**

My callback now uses `array_unshift($form['#submit'],'my_callback')` and via `drupal_http_request`, is submitting to both websites. However, my webform is still not saving submissions locally, and instead on submit, redirects to self (even with no `hook_form_alter`).

# Answer
EDIT: added option (1) after thinking about this more, haha. It's a much simpler solution.

**(1)**

If the below is to complex you (and you actually want to POST something) you could form\_alter the form and **append** your own additional FAPI `#submit` function which uses `drupal_http_request()` to POST/GET the url with all the submitted form params.

**(2)**

I think you want to set the `destination` value from within the `#action` of the form to be wherever the default webform submit path is and tag on a `destination` querystring parameter to the action which drupal will then goto after the form has been validated/submitted.

I know you said you tried using `#action` but I'm talking about the action being the drupal action and destination being a remote url (url-escaped).

Eg, I have customized a login form to use various login backend logic depending on the url of the login: /user/login, /student/login, /staff/login ... etc. I then make the destination of a succcessful login goto a specific drupal page. `destination` is used by drupal\_goto() to redirect the user anywhere -- even an external url.

Here is a small example from code I have in D7:

```
/**
 * The following 2 functions allow our form overrides to occur.
 */
function MYMODULE_form_user_login_block_alter(&$form, &$form_state) {
  if (_MYMODULE_auth_is_student_login_page_url()) {
    $form = $form + array('#auth-destination' => 'student');
    _MYMODULE_auth_user_login_form_alter($form, $form_state);
  }
  if (_MYMODULE_auth_is_staff_login_page_url()) {
    $form = $form + array('#auth-destination' => 'staff');
    _MYMODULE_auth_user_login_form_alter($form, $form_state);
  }
}

function MYMODULE_form_user_login_alter(&$form, &$form_state) {
  if (_MYMODULE_auth_is_student_login_page_url()) {
    $form = $form + array('#auth-destination' => 'student');
    _MYMODULE_auth_user_login_form_alter($form, $form_state);
  }
  if (_MYMODULE_auth_is_id_login_page_url()) {
    $form = $form + array('#auth-destination' => 'staff');
    _MYMODULE_auth_user_login_form_alter($form, $form_state);
  }
}

function _MYMODULE_auth_user_login_form_alter(&$form, &$form_state) {
  global $conf;
  $saveForm = $form;
  $form = array();
  # overrides the default validator.
  foreach ($saveForm as $key => $value) {
    if ($key == '#validate') {
      $form[$key] = array();
      foreach ($value as $validator) {
        if ($validator == 'user_login_authenticate_validate') {
          // If we progressed down to this level of nested Alters, we have
          // #auth-destination.
          $type_of_login = $saveForm['#auth-destination'];
          switch($type_of_login) {
            case 'staff':
              // These functions are custom validate functions whose logic is
              // copied/altered from the default
              // 'user_login_authenticate_validate' implementation.
              $validator = 'MYMODULE_auth_staff_authenticate_validate';
              // the form posts back to itself and supplies a unique destintation.
              $form['#action'] = '/?q=staff/login&destination=%3Cfront%3E';
              break;
            case 'student':
              $validator = 'MYMODULE_auth_student_authenticate_validate';
              // the form posts back to itself and supplies a unique destintation.
              $form['#action'] = '/?q=student/login&destination=student/my-surveys';
              break;
            default:
              break;
          }
        }
        $form[$key][] = $validator;
      }
    }
    else {
      $form[$key] = $value;
    }
  }
  $form['name']['#title'] = ($type_of_login == 'Staff') ? 'Staff Username' : 'StudentCampusID';
  unset($form['links']);
}

```
> 2 votes

---
Tags: webforms, forms
---


# Question
Title: Show comment module but have it disabled for anonymous users
I have what I believe is a slightly unusual requirement for comments. I'm trying to figure out how to implement this:

1. Comment form should always appear at the bottom of the page (this helps users understand they can submit a comment especially if there are no comments yet for a given article)
2. If the user is registered the comment form should be enabled.
3. If the user is anonymous the comment form should be disabled and provide a link to registration

It seems like the comment module is generally built to be on or off. Any recommendations on exposing it as a disabled form?

# Answer
I didn't know this until I just tried it but you can use a `hook_form_alter()` function in a custom module and simply set the whole `$form` to disabled...this disables all child elements as well. Combine it with the `user_is_anonymous()` function and you should be set:

```
function MYMODULE_form_comment_form_alter(&$form, &$form_state, $form_id) {
  if (user_is_anonymous()) {
    $form['#disabled'] = TRUE;
    // Add a link:
    $form['register_link'] = array(
      '#markup' => l('Click here to register...', 'user/register')
    );
  }
}

```
> 3 votes

---
Tags: comments, users
---


title: Table v.s., node

text:
# Question
Title: Table v.s., node
I am migrating from Drupal 6 to Drupal 7 and have the opportunity to restructure data.

Assume storage of contacts: A node was created of type contact, but information was stored, such as birthday, in other fields. I didn't design it and don't know why another field wasn't added to the node via CCK.

Nonetheless, is there any reason from a performance standpoint to create a table called "contact" and store all relent information there (e.g., is there performance overhead in using the "node" structure v.s., a simple table - and yes, I know a node is a table).

The database engine in use is MySQL.

# Answer
Yes - there is definitely a performance overhead to dealing with your content in Drupal nodes / cck vs using a simple table, assuming you are keeping all of your contacts data in that one table. The performance overhead comes from the abstraction built into the CCK system that requires complex SQL queries to construct your data record from multiple tables (ex. fields, input formats, other modules).

For the most part, you probably want to use CCK because it makes it easier to manipulate this data and add new fields and it exposes your data to dozens of other modules. If this performance hit is an issue you can counteract it by using caching at either the mysql, php, apache, or drupal layer. Otherwise, you can keep your data in a simple (non-drupal) table and expose it to views and other modules by using the Data module.

And Last but Not least, you can run your own storage strategy for a node it the standard fields approach is not enough.
> 1 votes

---
Tags: nodes, theming
---