title: multilingual nodes architecture issue

text:
# Question
Title: multilingual nodes architecture issue
Is it possible that node translations aren't new nodes? For example if I translate `/node/1` I get `/node/2` and this is problematic in some cases (comments are not shared between #1 and #2, and entity references are not reused).

Detailed walkthrough:

I'm using `locale`, `translation`, `variable` and `i18n`. I've got 2 languages configured: `EN`, `FR`. I have content types `News` and `Event`. Both have Multilingual support: "Enabled, with translations". The `News` has fields:

* title
* body
* reference to a `Event` (implemented with `entityreference`)

I create 2 node instances:

* /node/1 (#1) Event (EN)
* /node/2 (#2) News (EN) with reference back to #1

I edit #1 and add a translation (FR) and #3 is created. I then translate #2 and #4 is created. The problem is that I have to respecify that the reference from #4 is #3 and not #1. If I use the "Synchronize translations" feature of the content type the workflow is a bit better but still not exactly what I want since on the FR front end when viewing #4 the reference to #1 will be displayed in EN and not FR.

Is there any way to have translations not creating new nodes but instead just translating some fields only?

Also, is the module `i18n` the "defacto standard" for implementing multilingual sites in Drual 7? Or is there something better out there?

# Answer
Did you try Entity Translation ?

I find it very much easier and efficient than i18n (which is needed for some other parts of the site anyway).

There you get exactly what you're looking for : translations stored in one node only.
> 2 votes

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


# Question
Title: How to set a "must be greater than a value" condition in Rules
I need to check with the Rules module whether a field is greater than some value. To be more precise, if the size in cm of a product (the field size is created through the Commerce Physical module) is \> than 5000.

How can I do this? I tried to add a 'Data comparison' but i only get "equals" or "is one of" when i select the comparison operator. I would have expected an "is greater than".

# Answer
> 2 votes
Check what kind of field you have. If you have an Integer field, "is greater than" and "is less than" will be available for `Data comparison`. Perhaps you mistakenly set it to text? If so, you may need to delete the field and create it again.

---
Tags: 7, rules
---


title: White screen, header information

text:
# Question
Title: White screen, header information
I'm getting the following errors after I modified my custom module.

> warning: Cannot modify header information - headers already sent by (output started at /home/rssmgovu/public\_html/blackbox.tv/BB/sites/all/modules/custom/custom.module:1) in /home/rssmgovu/public\_html/blackbox.tv/BB/includes/session.inc on line 98.
> warning: session\_regenerate\_id() \[function.session-regenerate-id\]: Cannot regenerate session id - headers already sent in /home/rssmgovu/public\_html/blackbox.tv/BB/includes/session.inc on line 101.
> warning: Cannot modify header information - headers already sent by (output started at /home/rssmgovu/public\_html/blackbox.tv/BB/sites/all/modules/custom/custom.module:1) in /home/rssmgovu/public\_html/blackbox.tv/BB/sites/all/modules/custom/custom.module on line 194.

The code of my module is the following one.

```
function custom_init() {
  drupal_add_js(drupal_get_path('module', 'custom') . '/js.js');
}

function custom_perm() {
  return array("register access", "access download", "access terms");
}

function custom_menu() {
  $items['user_signup'] = array(
    'title' => '',
    'page callback' => 'custom_page',
    'access arguments' => array('register access'),
    'type' => MENU_CALLBACK,
  );

  $items['download-file'] = array(
    'title' => '',
    'page callback' => 'download',
    'access arguments' => array('access download'),
    'type' => MENU_CALLBACK,
  );

  $items['terms'] = array(
    'title' => 'NON-DISCLOSURE AGREEMENT',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('custom_full_form'),
    'access arguments' => array('access terms'),
  );

  return $items;
}

function custom_full_form() {
  global $user;
  $uid = $user->uid;
  $qry = db_fetch_array(db_query("select mail from {users} where uid=" . $uid));
  $sql = db_query("select fid, value from {profile_values} where uid=" . $uid);
  while ($rqy = db_fetch_array($sql)) {
    if ($rqy["fid"] == 3) {
      $ln = $rqy["value"];
    }
    else if ($rqy["fid"] == 4) {
      $fn = $rqy["value"];
    }
  }

  $form['terms']['first_name'] = array(
    '#type' => 'textfield',
    '#title' => t('First Name'),
    '#size' => 20,
    '#maxlength' => 128,
    '#prefix' => '<div class="fname">',
    '#suffix' => '</div>',
    '#default_value' => $fn
  );

  $form['terms']['last_name'] = array(
    '#type' => 'textfield',
    '#title' => t('Last Name'),
    '#size' => 20,
    '#maxlength' => 128,
    '#prefix' => '<div class="lname">',
    '#suffix' => '</div>',
    '#default_value' => $ln
  );

  $form['terms']['mail'] = array(
    '#type' => 'textfield',
    '#title' => t('E-mail'),
    '#size' => 20,
    '#maxlength' => 128,
    '#prefix' => '<div class="femail">',
    '#suffix' => '</div>',
    '#default_value' => $qry['mail']
  );

  $form['terms']['check'] = array(
    '#type' => 'checkbox',
    '#name' => 'terms_checkbox',
    '#title' => t('I accept the terms'),
    '#prefix' => '<div class="terms_check">',
    '#suffix' => '</div>'
  );

  $form['terms']['decline'] = array(
    '#type' => 'submit',
    '#value' => t('Decline'),
    '#prefix' => '<div class="decl">',
    '#suffix' => '</div>'
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Accept'),
    '#prefix' => '<div class="acc">',
    '#suffix' => '</div>',
    '#disabled' => true
  );

  return $form;
}

// function custom_full_form_validate($form, &$form_state) {}

function custom_full_form_submit($form, &$form_state) {
  global $user;
  $uid = $user->uid;
  $last_name = $form['terms']['last_name']['#value'];
  $first_name = $form['terms']['first_name']['#value'];
  $mail = $form['terms']['mail']['#value'];
  $fid_last_id = 3;
  $fid_first_id = 4;
  if ($form_state['values']['op'] == 'Decline') {
    drupal_goto("logout");
    exit;
  }
  elseif ($form_state['values']['op'] == 'Accept') {
    $_uid = db_fetch_array(db_query("select uid from {profile_values} where fid=$fid_first_id and uid=".$uid));
    if (empty($_uid)) {
      db_query("insert into {profile_values}(fid,uid,value) values($fid_last_id,$uid,'" . $last_name . "')");
      db_query("insert into {profile_values}(fid,uid,value) values($fid_first_id,$uid,'" . $first_name . "')");
    }
    else {
      db_query("UPDATE {profile_values} SET value='" .$last_name. "' where uid='".$uid."' and fid=".$fid_last_id);
      db_query("UPDATE {profile_values} SET value='" .$first_name. "' where uid='".$uid."' and fid=".$fid_first_id);
    }
    db_query("UPDATE {users} SET mail='" . $mail . "', init='".$mail."' where uid=" . $uid);
    db_query("UPDATE {users} SET accept=1 where uid=" . $uid);
    drupal_goto("download");
    exit;
  }
}

function download() {
  $filename = $_GET['file'];
  header("Content-Length: " . filesize($filename));
  $ending = end(explode(".", $filename));
  if ($ending == 'air') {
    header('Content-Type: application/air');
    header('Content-Disposition: attachment; filename="' . $filename . '"');
  }
  else {
    header('Content-Type: application/pdf');
    header('Content-Disposition: attachment; filename="' . substr($filename, 15) . '"');
  }

  watchdog("downlaod", $filename . " was downloaded");
  readfile($filename);
  exit;
}

function custom_page() {
  return "";
}

function custom_login_forgot_password() {
  $path = drupal_get_path('module', 'user') . "/user.pages.inc";
  include $path;
  return drupal_get_form("user_pass");
}

function custom_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == "user_login_block") {
      $item = l(t('Lost your password?'), 'user/password/forgot', array('attributes' => array('title' => t('Request new password via e-mail.'))));
      $form['links'] = array('#value' => $item, '#weight' => 10);
      $form['submit']['#value'] = '';
      $form['#submit'][] = 'custom_login_submit';
  }
  elseif ($form_id == "custom_full_form") {
    $form['terms']['first_name']['#title'] = "";
    $form['terms']['last_name']['#title'] = "";
    $form['terms']['mail']['#title'] = "";
  }
}

function validateFormSubmit() {}

function custom_login_submit($form, &$form_state) {
  global $user;
  $sql = db_fetch_array(db_query("select accept from {users} where uid=" . $user->uid));
  if ($sql['accept'] != "" && $sql['accept'] != 0) {
    header("location:/BB/download");
    exit;
  }
  else {
    header("location:/BB/terms#content");
    exit;
  }
}

/*
function custom_user_register_validate($form, &$form_state) {
  user_module_invoke('validate', $form_state['values'], $form_state['values'], 'account');
}
*/

function custom_block($op = 'list', $delta = 0, $edit = array()) {
  global $user;
  $block = array();

  switch ($op) {
    case 'save':
      break;

    case 'list':
      $block['custom_user_login']['info'] = t("custom User login");
      /*$block['custom_user_register']['info'] = t("custom User register");*/
      return $block;
      break;

    case 'view':
      if ($delta == "custom_user_login") {
        if ($user->uid == 0) {
          $block['subject'] = t("");
          $block['content'] = drupal_get_form('user_login_block');
        }
      }
      /* elseif ($delta == "custom_user_register") {
        $block['subject'] = t("");
        $block['content'] = drupal_get_form('user_register');
      }*/

      return $block;
      break;
  }
}

function custom_preprocess_block(&$vars) {
  if ($vars['block']->delta == "custom_user_login") {
    $vars["template_files"][] = "block-custom-user";
    $vars['block']->htmlid = "block-custom-login";
  }
}

```

# Answer
> 2 votes
If you read the error message, you can see

> output started at ... /custom.module:1

You have some manner of output at the top of your file. Have you pasted the file exactly as it is written? If so, it's probably an encoding problem, possibly a so called BOM-character. Try re-saving the file in just ascii format.

---
Tags: 7
---


# Question
Title: How to make one node relate to another node?
Ok, I'm going to toss out an example of what I'm trying to do with US states and counties, but I'm not looking for a module to handle them... It's just an example.

Assume I have two content types, the US State and US County content types. So now I have some nodes of US State (alabama, alaska, etc) that have some fields, like maybe population size, square feet of territory, etc. Now I have counties, so I've got some N counties that belong to alabama, some for alaska, etc., each as its own node.

How can I make a US County node know what US State node it belongs to? How can I make US State nodes know what US County nodes belong to them? For like querying in a view or whatever, basically the functionality of foreign keys in a SQL table. This seems like it would be very simple and obvious to do, but I must be missing it.

Remember, this is just example data types, I'm not really working with US States and US Counties, so I don't want some specific module for them, just the idea of how to setup content types and the like to have foreign keys.

And if anyone knows, how efficient is this? If I'm dealing with millions or maybe billions of nodes with some hierarchy of relations, how well can drupal query this stuff with joining linked data from multiple content types based on these "foreign keys"? Is it 10x slower than mysql tables with foreign keys, faster than that?

edit: Using Drupal 7. Maybe this will make things clearer: I've tried making a taxonomy vocabulary or whatever, but I don't see how to specify relations between nodes. I can say a US County is under US State, but how can I say "Baldwin County" is in "Alabama"? Where do I put that data in?

# Answer
Relating US Counties to US States sounds like something Taxonomy would be great at, considering it has built in Hierarchy.

However, for Node Relations the best module for the job is References. If you will have users adding content that will reference another node, you can utilize Node Reference URL Widget. That will allow you to, for instance, create an "add county" link, which when clicked brings the user to an add county page that is already populated with the correct state.
> 0 votes

# Answer
I'd look into Node References or Taxonomy depending on what version of drupal you are using and whether or not you are trying to create a hierarchy structure in your site.
> 0 votes

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


# Question
Title: More on recommendable caching practices?
Having read this Q & A, I feel like asking some more, perhaps very basic, questions anyway.

I'm just about to deploy a taxonomy- and Views-intensive site, and I'm wondering about the best cache practices with regards to Drupal and Views configuration.

Needless to say that all my caches are turned off for the purpose of reliable development, but for the sake of speed and server efficiency, some caching should be enabled when the site goes live.

The following questions come to my mind:

1. Should the `Expiration of cached pages` and `Minimum cache lifetime` settings depend on the frequency of adding content to the site?
2. Is it possible to broadly define types of Views that should have their cache turned on? and which should not?
3. If you were to turn the cache on, where would you do that: on the production site, or the development one before deployment?
4. Has anybody developed a comfortable operational pattern using a staging and production sites using Deploy module, with regards to cache? If so, what practice do you recommend?

# Answer
There is great info on views caching on this Q&A. It should answer your questions 1-3. The 4th should probably be asked as a separate question.
> 0 votes

---
Tags: 7, caching
---


# Question
Title: How to use tokens in php code of the rules module?
I'm using Ajax\_comments to add comments on nodes without having to reload the page on save. Now the "node history" doesn't get updated which throws off the "new comment" count.

I tried to create a rule to update the node history on "comment save". Seems like my only option is to execute PHP code. How do I combine PHP code with tokens to get something like this:

```
if ([current-user:uid]) {
   db_merge('history')
     ->key(array(
       'uid' => [current-user:uid],
       'nid' => [comment:node:nid],
     ))
     ->fields(array('timestamp' => [site:current-date]))
     ->execute();
  }

```

# Answer
It turns out that the above code works when I turn of the Ajax Comments module. With that module, it throws an internal server error.

I reported it as issue.

This hook does the job now:

```
function hook_comment_insert($comment) {
  //dpm($comment);

  if ($comment->uid) {
   db_merge('history')
     ->key(array(
       'uid' => $comment->uid,
       'nid' => $comment->nid,
     ))
     ->fields(array('timestamp' => REQUEST_TIME))
     ->execute();
  }
}

```
> 3 votes

---
Tags: 7, rules, tokens
---


# Question
Title: Authenticated users can't view the front page
I set `node/4` as the front page on the Site Information screen.

This works for anonymous users, but authenticated users cannot access the front page (node/4). Even if they manually type `www.site.com`, they are redirected to `www.site.com/user/4`.

Please help me out.

# Answer
I found the issue: I am using `drupal_render('user_login')` inside a template, which is redirecting to a "user/%" page, once the user is logged-in.
> 0 votes

# Answer
Building on Patrick Kenny's comment, I'd recommend looking for the 'URL redirects' page within your admin pages. (You will have this page if you've installed a module which supports URL redirects - 'Redirect' in D7, 'Path redirect' in D6.) Then see if any rule is defined there which'd redirect visitors from site.com/node/4 to site.com/user/4 .

If this module isn't doing this, odds are another one is, so as Patrick says start disabling contrib modules one by one.
> 0 votes

---
Tags: 6, users
---


title: Module used to redirect pages to SSL

text:
# Question
Title: Module used to redirect pages to SSL
Is or are there currently a module(s) that redirects users of a drupal site to enforce a SSL connection on parts of the website?

Essentially accomplish the following use case:

> A user visits a glob pattern: /cart/\*, / it enforces https:// connection as well as redirects any images/javascript to utilize a ssl connection.

# Answer
Looks like this is currently the canonical answer:

Use Secure Pages

> This module makes sure that the user is running on a secure page when they create or edit content, view user details, or administer the site.

The other part of my question regarding redirecting assets on a page to a secure connection has actually be integrated into drupal core. It was previously a contrib module: http://drupal.org/project/securepages\_prevent\_hijack

> #D7CX: This functionality is in Drupal 7 core so this module will not be ported. Please stay tuned for the securepages port.
>
> This is an add-on to the Secure Pages module that will prevent hijacked sessions from accessing SSL pages, yet still allow users to stay logged in when browsing non-SSL pages.

Drupalscout looks to have a great site recipe on working with SSL's as well:

> The Secure Pages module is a relatively old module and quite popular. It's goal is to only make certain pages of the site use HTTPS by using two lists of urls which should either by HTTPS or not. The benefit of this module is that you can use regular old HTTP for most of the site and only encrypt the traffic where you really need it. By default it will encrypt traffic for adding content, editing content, anything related to users, and for the admin area.
>
> SSL processing is taxing on a server. Using SSL on just the most important pages helps make sure that the data sent back and forth on those pages is encrypted. However, the session cookie is still unencrypted so a user who authenticates over HTTPS and then visits a non secure page sends their sesssion identifier in the clear which allows for an attacker to steal their session and login to the site which gives them the access to the very data that was supposed to be protected. This is largely "security theater" but it sure makes people feel good.
>
> Pro: Reduces load on server compared to a full SSL solution while encrypting important data transmission. Con: Doesn't protect against session hijacking so data can still be compromised.
> 1 votes

---
Tags: 7, commerce
---


title: Search Including Node Taxonomy Field

text:
# Question
Title: Search Including Node Taxonomy Field
I have a content type with a taxonomy field on it that needs to be included in the standard search of Drupal 7.

Is there a way to do this or do I have to set up a view to override the standard search?

If I do have to use a view, how can I set it up to allow searching all fields on a node from one text field in the search form?

I thought Drupal did this with it standard search but it doesn't seem to.

# Answer
If you choose "Node" as an active search module it will index the full node including taxonomy terms:

Here you can see the tag "bros" is returned in the core search:

Are you sure that the site is fully indexed?
> 5 votes

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


title: Inserting a carriage return into t()

text:
# Question
Title: Inserting a carriage return into t()
How can I put a carriage return into the drupal t() function in Drupal 6? I tried using `\n` and that didn't work, which seems to make sense after reading the documentation for the function.

# Answer
Never had a usecase for that and no working Drupal 6 installation, but I assume your problem isn't `t()` related, more PHP related.

```
<?php

// This does not work!
echo '\n';

// This does work on UNIX!
echo "\n";

// This does work on Win!
echo "\r\n";

```

Hope this answers your question and helps.
> 1 votes

---
Tags: emails
---


# Question
Title: Goal: 1 Webform as Block, Multiple Nodes with block in Panel pane
I am trying to create a single webform that I can expose as a block and re-use on multiple 'profile' nodes. These nodes will use Panels and Panel/Panes to display content.

Problem: I need to pass email address(s) stored on the "parent"('profile') node (cck fields perhaps) to the "child" webform so that the form is sent to the address(s).

I've tried following a few articles that said to create a custom module to implement hook\_form\_alter. I haven't been able to get it to work. I'm a bit of a noob at the whole programming side of Drupal so any help would be appreciated.

# Answer
> 1 votes
You can create a view for this web form node, and display it as block. This will work.

# Answer
> 0 votes
In D7, you could go to "/node/%nid/webform/configure". Here under the "Advanced Settings" Tab, you could check the box "Available as block ". Your web-form will be available as a block now.

To pass the email address to the webform block, you could try using the Webform Token along with the Token Module.

---
Tags: 7, webforms
---


# Question
Title: howto set a category for a webform/entityform question ...?
I need to have students fill out ~50 questions on their studies abroad -- and show their answers on pages in drupal (form submissions are drupal content). questions can belong to 10 different categories. I'm trying to use either webform or entityform ... but coming up blank here on how to give each question an associated category Views can use.

I can use field\_group to group questions under a specific category, but the `field_group` setting is not useable in Views. I'm aiming for a view of something like this photoshop mockup:

Any ideas are appreciated :)

I have looked into making a Views Filter for the field\_group field. But field\_group stores the data for a group in a serialized `$data` field per Group ... I dont think views as an sql-query-builder can do anything meaningful with data in that format (or am I wrong) ... ?

# Answer
You can do this with the Webform Entity module. It uses Webform to create the forms but the content that is created is a full-fledged entity instead of just a serialized array in the database. That means full Views support etc.

For a category you can use a field list in the webform which can become a taxonomy field or field list in the entity that can be used as an exposed filter in Views.

To set this up just go to "admin/config/content/webform/entities/webform/" and click "Create" to create an entity webform

Then add fields to the entity:

Now, when you create a webform, the fields from the webform entity will appear on your node:

Finally, in Views, create a new view with the webform subsmissions as a base table:

and the fields attached to webforms can be used as exposed filters, fields and all other things views:
> 1 votes

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


# Question
Title: Caching issue with View and anonymous users
Our site uses Views heavily and unfortunately we've got a caching problem.

On our front page we've got a View that only shows content whose publishing date is more recent than the current date. So if we post an article whose publishing date is 2 hours from now, it should be visible in two hours from now on.

This works fine for logged in users. But the majority of our visitors doesn't have an account. And when not logged in the article gets published seemingly at random. It could be visible 20 minutes or 1 hour past the desired date.

The View has got no caching enabled. Site wide we've got the following options enabled:

* Caching mode: normal
* Page compression
* Block caching
* CSS caching
* JavaScript caching

Do you have some hints regarding our problem? I'm using Drupal 6.

# Answer
Reposted a new answer to suggest maybe using scheduler module to set the desired publish date for individual nodes.

Content will be published automagically on your specified date. Works great.

* You can also use workflow, rules and actions to achieve same function, albeit with more overhead.
> 0 votes

# Answer
Here is a small hack to prevent some pages from being cached for anonymous users:

```
// Prevents frontpage caching
if (drupal_is_front_page()) {
  $GLOBALS['conf']['cache'] = FALSE;
}

```

Hope this helps, cheers!
> 1 votes

# Answer
The problem is that the content not appearing is unpublished, which Drupal will hide until it is published.

You can circumvent this in two ways:

1. In Views make sure there is no filter for "Content: Published (Yes)". If there isn't one, then you can also disable Node Access checks. Under Advanced \> Other \> Query options, check Disable SQL Rewriting.
2. Install the "View Unpublished" module, and allow Anonymous users to view the unpublished content.

And I would leave your cache the way it is currently, will greatly help site performance and stability under load.
> 1 votes

# Answer
I've deactivated the page cache now (setting *caching mode* to *deactivated*) and this solved my problem.

As written in the description, the page cache affects pages called by guests (i. e. not authenticated users). Since I don't want those pages to be cashed, I've deactivated this feature.

I hope that the performance won't suffer that much.
> 0 votes

# Answer
Not sure, if this is what your looking for Views Content cache. But its worth a check out.
> 0 votes

# Answer
If your looking to dive deep into boost configuration it will handle this use case fairly well. We have the same issue at work. I don't have the time to help you set it up though. http://drupal.org/node/784676
> 0 votes

---
Tags: views, caching, nodes
---


# Question
Title: How to handle GET parameters in the proper Drupal way
I am working on a module that will handle the email subscription functions for our newsletters.

Email newsletters are sent out to subscribers with a link on them for them to unsubscribe. This link is in the format `http://www.site.com/opt-out?email={email_address}`. This is how the links are formatted and I can't change that.

What is the proper way to deal with that parameter using Drupal? Of course I have access to `$_GET['email']`, but is this the proper way of accessing it in a Drupal module? What about input filtering? Should I just do a plain `$email = filter_var($_GET['email'], FILTER_VALIDATE_EMAIL);` ?

# Answer
In many cases, there are standard Drupal functions that do validation. For example, for email addresses there is valid\_email\_address.

Otherwise, there is the standard PHP Data Filtering library (many of the Drupal validation functions actually use this).

I am a little torn, though, on which to use when directly accessing `$_GET` or `$_POST`. Lately, I have preferred using filter\_input, because it can check that the variable exists and validate in one step, and because it also makes it easy to switch between the different input sources (URL parameters, cookies, etc) which can be handy at times.

```
$email = filter_input(INPUT_COOKIE, "email", FILTER_VALIDATE_EMAIL);
if ($email === NULL) $email = filter_input(INPUT_GET, "email", FILTER_VALIDATE_EMAIL);

if ($email === FALSE) {
  handle_the_error();
} else {
  do_something_awesome();
}

```
> 2 votes

# Answer
When faced with this url structure, you can use $\_GET in the usual `PHP` way. Drupal urls are usually generated with parameters separated by `/`, and as you probably know, arg() is the right tool when this is the case.

As for the email validation, there are native functions that validate, but the validation is quite basic:

```
//check if this is a valid Drupal username
user_validate_name('USERNAME');

//check if this is a valid email address
user_validate_mail('test@test.com');

```

If you had to do this in a form, one can add validation functions where needed with hook\_form\_alter:

```
/**
 * Implementation of hook_form_alter().
 */function my_module_form_alter(&$form, $form_state, $form_id)  {
 if ($form_id == 'user_profile_form') {
  array_unshift($form['#validate'], 'email_check_validate');
 }
}

/**
 * Validate profile form
 * Force form error if new email address matches current email address
 *
 */
function email_check_validate ($form, $form_state)  {
  global $user;
  $old_email = $user->mail;
  $new_email = $form_state['values']['mail'];

  if ($old_email ==  $new_email) {
    form_set_error('mail', t('Your email could not be changed'));
  }
}

```

But this does not apply in your case, it was just an example for when you need to do validation through a form.

Hope this helps, cheers!
> 2 votes

---
Tags: 7
---


# Question
Title: D7 + Views 3 - How to reproduce a teaser with fields in Views
I need to build a "News" block on a website that shows teasers of certain categories.

BUT I cannot use teaser views because I don't want the styles that are in a teaser view. This rules out the`viewsnodefield` module and teaser option available in the first page of view creation.

My question is: how to reproduce a teaser using fields? How do I get the teaser content? How can I rewrite the link by surrounding the url link field?

Thank you for your thoughts

# Answer
You can use Display suite and Views to achieve the required functionality. Using Display suite, you can control what fields appear in the teaser. Also, Display suite provides views Integration, so you can use your new teaser to show up in views. This article explains more about this.
> 4 votes

# Answer
Rather than reproduce the teaser, you could use the Entity View Mode module to create a new view mode for your node type (alongside Default/Teaser). You could then set that up with exactly the same field layout as the teaser view mode, and use your new view mode for the display in your View, instead of teaser.

The CSS classes generated shouldn't contain `teaser-...` so the content can be styled separately.
> 3 votes

# Answer
You could implement hook\_entity\_info\_alter in a custom module, define a new view mode, and then use this in your view instead of fields. This is a decent tutorial on them, but the basics are to define the new view mode:

```
function mymodule_entity_info_alter (&$entity_info)
{
  $entity_info['node']['view modes']['abridged'] = array(
    'label' => t('Abridged'),
    'custom settings' => TRUE,
  );
}

```

Then your new view mode shows up on the **Manage Display** tab for your content types. Set up the view mode as you wish. Then, in your view, choose **Node** row style, and pick your new view mode. Combine this with a template\_preprocess\_node, and you get a lot of flexibility. Once I stated dong this, I pretty much stopped using individual fields in views, except for the simplest things.
> 0 votes

---
Tags: views, entities
---


# Question
Title: Multilingual websites- one menu for each language or one menu for all languages?
On a multilingual website, why would I use the i18n\_menu module to translate the menu items of a menu instead of simply making separate menus for each language? I read Gabor Hojtsy's excellent article on the menu system in D7 but I still don't understand in what sort of use case I would want to use i18n\_menu vs. simply creating separate menus for each language and setting them to display only for their respective languages.

# Answer
You have a lot more flexibility when using one menu for each individual language. It's a bit more work to setup but it definitivly pays out in the long run.
These are the points that are blocking me for using one translatable menu:

- You're not able to reorder menu items for only one language.
- You can't deactivate one particular link in one language, the content needs to be disconnected from the link.

Bottom line is when you're sure that you have a fixed menu that doesn't need flexibility it's OK to use i18n\_menu.
When building a site that could be expanded in the future and has differences between language content avoid the use of i18n\_menu and set up a menu for each language. (You can set a fixed language in order to do some ajax magic and only show the menu items available for each language when creating new content.)
> 1 votes

# Answer
I think the main interest of going for multilingual menu vs one per language is the maintenance cost.

It of course depends on the number of languages you have to manage. Two or three is OK, but if you have say eight languages to set up, things can become very complicated with several menus.

Also, node related menus are hard to handle with non i18n solutions.
> 1 votes

---
Tags: i18n-l10n
---


# Question
Title: What extensions are used in a module, and what do they mean?
I suppose there's a drupal page somewhere that explains this, but I can't find it.

When creating a module, you can have files that end with .module, .info, .inc, etc...

What are all the file extensions that are recognized and what do they do?

# Answer
> 8 votes
The extensions that are specific for Drupal, or that have a specific meaning in Drupal, are the following ones:

* The **.api.php** extension is used for the file describing the hooks used by a module, such as system.api.php.
* The **.install** extension is used for the file that is used when a module is installed, such as system.install. It is also loaded when Drupal is verifying the requirements needed from a module.
* The **.inc** extension is used for any secondary file that contains code that is loaded only when necessary. If the code is used in specific cases, such as when a specific menu callback is being invoked, then the code is moved in a separated .inc file. Often, you will find modules using a file with the **.admin.inc** extension (e.g. node.admin.inc) that includes all the code necessary to run the administrative interface, and a file with **.pages.inc** extension (e.g. node.pages.inc) that contains the code executed for other menu callbacks. If a module implements tokens, in Drupal 7 you will find files using **.tokens.inc** as extension (e.g. user.token.inc); those are the files where the implementations of hook\_token\_info(), and hook\_tokens() are looked for (see system\_hook\_info()).
* The **.info** extension is used for the file describing the module, or the theme, such as system.info. It contains metadata, such as the required Drupal version, the minimum PHP version with which the module/theme is compatible, and other information specific for the module, or the theme.
* The **.module** extension is used for the main file of a module, such as system.module.
* The **.test** extension is used for the files containing the testing code (e.g. system.test), which is actually running on the SimpleTest framework.
* The **.theme** extension was used from themes not using PHPTemplate template engine. In Drupal 6 (and before) the extension was used from the chameleon.theme file; in Drupal 7, there aren't themes using that extension.
* The **.tpl.php** extension is used for the template files used from theme functions, such as node.tpl.php.

Third-party modules can use specific extensions, such as the following ones:

* The .views\_default.inc extension is used for files (e.g. node.views\_default.inc) containing the code to implement the default views used from a module that integrates with the Views module.
* The **.views\_template.inc** extension is used for files (e.g. node.views\_template.inc) containing the code for views templates.
* The **.rules.inc** extension is used for files containing code for integrating with the Rule module.

# Answer
> 5 votes
A quick googling of 'writing drupal modules' returned the following developer guides:

There is also a project, Examples for Developers, which gives lots of insight into module writing and best practices, etc. It has versions for multiple releases of Drupal as well.

With more respect to .inc files, the documentation for module\_load\_include() explains how Drupal includes them within modules. Basically they are the Drupal's way of breaking up modules into more manageable pieces. Otherwise, a complex module might have a gigantic .module file.

Also, sometimes modules don't need all of their code loaded; so, code that is only called in certain routines is delegated to a .inc file for performance reasons and loaded only when needed.

If screencasts are more helpful, you might want to check out Your First Module - A Mostly Painless Intro to Drupal Development and click on the screencast link.

Bob over at http://mustardseedmedia.com/podcast has some great podcasts as well; most of his are D6, but he is getting more and more into D7.

# Answer
> 2 votes
A module conatins mainly 3 imp files

1. List item- .info file -\> a file which contains d module information like name version etc.
2. List item- .module file -\> a file that describes how a module works.
3. List item- .install file -\> this file is run for first time when the module is configured.this is maily to create database tables and the corresponding fields,this file has to be updated if we make any version change in module.

---
Tags: files
---


# Question
Title: Equivalent of created and modified properties for a taxonomy term
I am trying to do a query (using EntityFieldQuery) to get taxonomy terms created or modified in the last day.

for nodes, I use $query-\>propertyCondition('changed',$time\_interval, '\>='); but I can't find the corresponding property for a taxonomy term.

Any suggestion ? I need to be able to detect creation and modification of terms.

# Answer
> 1 votes
That data isn't stored for taxonomy terms, if you want to add it you'll need to write a small custom module to do so. You could look at implementing `hook_entity_info_alter()` or `hook_field_extra_fields_alter()` to actually add the extra property to the taxonomy term entity, but I haven't had much luck using that method before.

Instead I would define a table using `hook_schema()` in the .install file of your module:

```
function MYMODULE_schema() {
  $schema['taxonomy_term_extra'] = array(
    'fields' => array(
      'tid' => array(
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE
      ),
      'created' => array(
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE
      ),
      'modified' => array(
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE
      )
    ),
    'primary key' => array('tid')
  );

  return $schema;
}

```

Then in your module file implement the taxonomy CRUD hooks:

```
function MYMODULE_taxonomy_term_insert($term) {
  db_insert('taxonomy_term_extra')->fields(array(
    'tid' => $term->tid,
    'created' => REQUEST_TIME,
    'modified' => REQUEST_TIME
  ))
  ->execute();
}

function MYMODULE_taxonomy_term_update($term) {
  db_update('taxonomy_term_extra')
    ->fields(array('modified' => REQUEST_TIME))
    ->condition('tid', $term->tid)
    ->execute();
}

function MYMODULE_taxonomy_term_load($terms) {
  $result = db_query('SELECT * FROM taxonomy_term_extra WHERE tid IN (:tids)', array(':tids' => array_keys($terms)));
  foreach ($result as $record) {
    $terms[$record->tid]->created = $record->created;
    $terms[$record->tid]->modified = $record->modified;
  }
}

function MYMODULE_taxonomy_term_delete($term) {
  db_delete('taxonomy_term_extra')->condition('tid', $term->tid)->execute();
}

```

Now whenever you have a loaded taxonomy term you'll have access to `$term->created` and `$term->modified`. You can also use a normal `db_query()`, which is much faster than an `EntityFieldQuery` to get your filtered terms:

```
$args = array(':time' => strtotime('-1 day'));
$tids = db_query('SELECT tid FROM {taxonomy_term_extra} WHERE modified >= :time', $args)->fetchCol();

$terms = taxonomy_term_load_multiple($tids);

```

---
Tags: taxonomy-terms, database
---


title: Exposing fields for a search in Views

text:
# Question
Title: Exposing fields for a search in Views
I can add a filter for `node:title` and `node:body`, but then there's two separate search fields for the content. I also have some other exposed filters (checkboxes), but I need rather than two search fields to have just one normal search field. Any ideas on how to do this?

# Answer
> 2 votes
Here's the same issue on d.org.
In short: it's better to enable `Search: search terms` filter (Drupal core search module needs to be enabled too).

# Answer
> 2 votes
For Drupal 6, the Views Or module might be of assistance. You can set up one exposed filter to search multiple fields that way (though it's a little tricky, and dare I say hackish?). Here's a good tutorial from Krimson on this method.

The Search: search terms filter works great if you want to use core search (Core's 'search.module' must be enabled), and for most purposes, but if you want to do it for more advanced views, or without using core search (I rarely use it these days),

Another option is to use Computed Field to create a field containing all the data you'd like to search, and just use that field as the exposed filter field in Views (while *displaying* the other independent fields).

Finally, a hackish way that can work sometimes involves setting all the 'filter identifiers' to the same value (requires a views hack, at least while editing the view).

The best solution might be to write your own filter for Views... but that's pretty tough, especially with 3.x, as the API docs are in bad need of updating.

# Answer
> 2 votes
I found the Finder module to work like a charm.

It allows to searche multiple fields on users, as well as nodes. This is very convenient if you are trying to provide a user search field that goes through the whole profile.

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


# Question
Title: How to join two Drupal CCK content types in view without a node reference field, fast?
Users uploaded two **csv files** to create nodes for two CCK content types (Delivery Note and Payment), i.e.

```
 Delivery       Payment
----------     ---------
 Order No.      Order No.
 Recipient      Charge
 Address

```

I would like to create a view as a report for the boss:

```
 Order No.  Recipient  Charge
 ---------  ---------  -------
  ...        ...        $...
  ...        ...        $...
  ...        ...        $...

```

Order No. field is unique and both content types.

How's it possible to do it in Drupal's view?

---

The above question was asked on SO and I found a solution. However, the solution was way too slow (for example, it takes more than a hour to download ~2000 records via `Views Data Export`).

# Answer
> 1 votes
Since you don't have a reference between the two, Views has no way of knowing how the node's relate to eachother. Views has no direct support for joining on arbitrary columns.

So to solve this, you need to declare the relationship to Views your self. You do this by implementing hook\_views\_data, or in this case, since Views has likely already created most of the array, hook\_views\_data\_alter. The documentation for the first function has an example with code for a relationship.

---
Tags: 6, entities, views
---


# Question
Title: Creating an external authentication module
In Drupal 7, is it possible to make a module that handles user authentication without using the `user_external_login_register` method? (In other words, without saving the user in the Drupal database?)

Of course, Drupal will need the uid of the logged-in user, so my guess would be that this would be pretty hard if not impossible.

It would also require Drupal to do its checks on this external source every page load. So, would this require hacking the User module, or making something similar? Is that even possible?

# Answer
I stumbled on the exact same problem recently, and ended up using a generic user for all ones authenticated via the external system. It's the only way I see to manage this without creating a Drupal user for each external one.

Of course, it all depends about what you're trying to achieve. If you need to customize the website based on each individual user, you're out of luck with this solution. But then, if you need this level of granularity, you'd use a standard solution with automatic user creation, right ?
> 2 votes

---
Tags: users
---


title: How do I change a widget's markup?

text:
# Question
Title: How do I change a widget's markup?
I need to create another widget which acts exactly like a text field, but contains a button and link next to the element. How can I accomplish this?

I thought of two solutions.

* Copy the Text Module (with the Field Module) and look for the HTML
* Download the Autocomplete module and edit its markup

# Answer
In Drupal 7, to implement a new widget, you need to implement the following hooks:

`hook_field_widget_info()` returns information about the type of widget implemented, such as the fields supported from the widget and for which the widget can be used. An example of implementation is image\_field\_widget\_info().

```
function image_field_widget_info() {
  return array(
    'image_image' => array(
      'label' => t('Image'),
      'field types' => array('image'),
      'settings' => array(
        'progress_indicator' => 'throbber',
        'preview_image_style' => 'thumbnail',
      ),
      'behaviors' => array(
        'multiple values' => FIELD_BEHAVIOR_CUSTOM,
        'default value' => FIELD_BEHAVIOR_NONE,
      ),
    ),
  );
}

```

`hook_field_widget_form()` is the hook that returns the form field(s) necessary to get values for the field, which is what in Drupal 7 is called widget.
The reason you don't find any HTML in a module implementing a widget is that a widget is made of one or more form fields, which are defined using a form API array. If you look at file\_field\_widget\_form(), you will notice that it uses a managed\_file form field, but it also uses a theme function, and a form field process function.

```
  $element_info = element_info('managed_file');
  $element += array(
    '#type' => 'managed_file',
    '#upload_location' => file_field_widget_uri($field, $instance),
    '#upload_validators' => file_field_widget_upload_validators($field, $instance),
    '#value_callback' => 'file_field_widget_value',
    '#process' => array_merge($element_info['#process'], array('file_field_widget_process')),
    '#progress_indicator' => $instance['widget']['settings']['progress_indicator'],
    // Allows this field to return an array instead of a single value.
    '#extended' => TRUE,
  );

```

```
  if ($field['cardinality'] == 1) {
    // Set the default value.
    $element['#default_value'] = !empty($items) ? $items[0] : $defaults;
    // If there's only one field, return it as delta 0.
    if (empty($element['#default_value']['fid'])) {
      $element['#description'] = theme('file_upload_help', array('description' => $element['#description'], 'upload_validators' => $element['#upload_validators']));
    }
    $elements = array($element);
  }

```

As I said, a widget is used to get the value associated with a field; when you need to show the value associated with a field, you need to create a formatter through hook\_field\_formatter\_view(). See Field Formatter API for more information.
> 2 votes

---
Tags: 7, entities
---


# Question
Title: How can I insert Javascript right before the body in my custom theme?
I want to make the same jquery menu in my custom drupal theme but ***I could not insert the inline script*** right before the body.

I made a separate JavaScript file, and added to my custom .info file, but this is not the right way to insert inline JavaScript, obviously.

This is my info file.

# Answer
Not sure this helps but I had a similar problem before. I solved it by using the `jQuery` syntax instead of the `$`, like so:

```
jQuery(window).load(function() {
    jQuery('#a a').css({'background-position','-20px 55px'});
    // and so on
});

```

You could load your js file by calling the `drupal_add_js()` in the `THEME_preprocess_page()` hook in your template.php file.
> 1 votes

# Answer
```
drupal_add_js('jQuery(document).ready(function () { alert("Hello!"); });', 'inline');

```

Try with this refer here for more details : http://api.drupal.org/api/drupal/includes%21common.inc/function/drupal\_add\_js/7
> 0 votes

# Answer
If you really need to insert the JavaScript code right after the `<body>` tag, you can add the following code right after the `<body>` tag.

```
<script type="text/javascript">
  (function ($) {
    $(function () {
      $('#a a') // ...
    });
  })(jQuery);
</script>

```

I suspect you are asking because a dialog box opens reporting a warning. That is because you should wrap the code using the jQuery library with `(function ($) { /* Your code. */ })(jQuery);` as it is done with any JavaScript file used from Drupal, such as batch.js.

```
(function ($) {

/**
 * Attaches the batch behavior to progress bars.
 */
Drupal.behaviors.batch = {
  attach: function (context, settings) {
    $('#progress', context).once('batch', function () {
      var holder = $(this);

      // Success: redirect to the summary.
      var updateCallback = function (progress, status, pb) {
        if (progress == 100) {
          pb.stopMonitoring();
          window.location = settings.batch.uri + '&op=finished';
        }
      };

      var errorCallback = function (pb) {
        holder.prepend($('<p class="error"></p>').html(settings.batch.errorMessage));
        $('#wait').hide();
      };

      var progress = new Drupal.progressBar('updateprogress', updateCallback, 'POST', errorCallback);
      progress.setProgress(-1, settings.batch.initMessage);
      holder.append(progress.element);
      progress.startMonitoring(settings.batch.uri + '&op=do', 10);
    });
  }
};

})(jQuery);

```

Putting the JavaScript code inlined right after the `<body>` tag, inlined inside the `<head>` tag, or in a file doesn't normally makes any difference, especially if all the code does is waiting for the DOM being loaded, and calls one or more jQuery functions, as in your case.
> 0 votes

---
Tags: 7, javascript
---


title: How to Split content in drupal 7?

text:
# Question
Title: How to Split content in drupal 7?
I am new to drupal and drupal 7, I saw a video tutorial previous day regarding drupal 6, there they just used this:

```
print $content;
print $title;

```

to display post title and content separately however, in drupal 7 , I copied one of theme page.tpl.php file and there is only this:

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

```

This shows full content inlcuding everything, how do I split them into parts like:

I want to customize my template like this

```
<div id="leftHolder">

                        <h1>Welcome to My site // for header </h1>

                        <p>

                            Some text Portion //

                        </p>

 </div>

```

This should be same for individual page and front page that shows 2 or 3 posts.

I tried making custom node.tpl.php file too, should I add some special function call to make it able to load content from node.tpl.php file ?

I pasted this code in template to render from page.tpl.php file of my theme

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

```

# Answer
In page.tpl.php leave where ever you wants: `<?php print render($page['content']); ?>` and then use `node--YOUR_NODE_TYPE.tpl.php` and put content where ever you want. You habe `$node` object print it and see what variables it has. Make sure that you also have `node.tpl.php` \- initial template file in your theme folder.
> -1 votes

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


# Question
Title: How to display User profile fields to anonymous visitors?
Currently I am developing an application in Drupal 7 , and my requirement is to display User profiles(profile image,DOB,Course,Year of joining etc.,) to anonymous users . I have used profile2 module to store them in the Database. The same information I wanted to display when a visitor clicks any of the User link. But i stuck in this part.

Please assist me in solving this...!

Thanks in advance -Syam Kumar

# Answer
Normally this is simply done within the permissions admin section (`/admin/people/permissions` if I remember right). Simply give anon users the permission to view profiles and those fields.

Maybe the module you are using causes the fields to be hidden. Check the permissions of that module as well.
> 2 votes

# Answer
If you use some custom module by your own you can always use this:

```
profile2_load_by_user($UID, 'MACHINE_PROFILE_NAME');

```

use some of preprocess function and attach that data to your view page. You can add this also in your template.php file or you can add it to any other .tpl.php template file.

I always use custom link and past user UID to it, get all fields what I need and show in custom template file.
> 0 votes

---
Tags: entities, users
---


title: How to get the block by string ID

text:
# Question
Title: How to get the block by string ID
I have a block, and want to print it in the template. I use the following code:

```
 $block =  module_invoke('block', 'block_view', '6');
 print render($block["content"]);

```

It works, but in `module_invoke()` I use the ID of the block in the database, which is very bad. Is it possible to assign the string ID to the block and use it instead?

If it's impossible, how can I use strings instead of numbers?

# Answer
> 1 votes
Use this:

```
<?php print render(block_get_blocks_by_region('YOUR_REGION_NAME')); ?>

```

put this code in your .tpl file and make sure you add your block in that region.

# Answer
> 2 votes
There's no built-in function for loading a block by string, but you can use a simple SQL query to get the ID of the block using a string.

```
$block_name = "Your block name";

$block_id = db_query("SELECT bid FROM {block_custom} WHERE info=:info", array(":info"=>$block_name))->fetchField();

$block =  module_invoke('block', 'block_view', $block_id);
print render($block["content"]);

```

---
Tags: blocks
---


# Question
Title: Advanced conditions in Database Abstraction Layer?
I have a module with a custom schema in it. On my cron job, I want to delete records older than 90 days. There is a date field in the table that holds a unix timestamp.

The query I want to run is `DELETE FROM table WHERE UNIX_TIMESTAMP() - date > 778000`, where 7780000 is the number of seconds in 90 days.

To test my query, I tried to make a select query with the same conditions:

```
$results = db_select('table')
->fields('table', array('field'))
->condition('UNIX_TIMESTAMP() - date', 7780000, '>')
->execute()->fetchAssoc();

```

However, the database AL doesn't parse the conditional the way I want it to:

```
PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'UNIX_TIMESTAMPdate' in 'where clause': SELECT ...

```

How do I write this conditional properly in the database AL?

# Answer
You need to use the 'where' method for complex conditionals:

```
db_delete('table')
  ->where('UNIX_TIMESTAMP() - date > :date', array(':date' => 7780000))
  ->execute();

```
> 4 votes

---
Tags: database
---


# Question
Title: Where does the $node get its field values after a node edit page has been submitted?
I'm attempting to debug a problem where a date field is not being saved.

The field renders fine with the rest of the node form, but upon submit one particular field has no value.

The `$form_state` contains the expected value all the way down until the form does a redirect to the node view, however, in `hook_node_presave`, all the data that should be on the node, is missing.

I'm getting lost in the form api trying to trace down where exactly the `form_state` gets added onto the node.

I am using Drupal 7, and the Date module version 7.x-2.5.

# Answer
> 1 votes
It looks like the actual work to attach the fields to entity objects is done in the `_field_invoke()` function, right at the bottom with these lines:

```
if ($items !== array() || isset($entity->{$field_name}[$langcode])) {
  $entity->{$field_name}[$langcode] = $items;
}

```

That doesn't make a lot of sense out of context so it's worth having a look at the whole code for the function.

The basic workflow is:

1. The node form submit handler calls `field_attach_submit()`
2. `field_attach_submit()` calls `_field_invoke_default()`
3. `_field_invoke_default()` calls `_field_invoke()`

The entity object is passed through all of those functions and once they're run all fields are attached to the object.

I know it's not much to go on but hope it helps.

---
Tags: entities
---


# Question
Title: Back button gets stuck in a loop after submitting a new comment
I have a comment form shown below the comments list on a node page. I'm using pathauto for urls.

When I visit the page with the my-node-page#new link and then submit a comment it loads the node with a my-node-page#comment-1234. When I click the back button to get to the previous page I get to my-node-page#new. I click back again and get to my-node-page#comment-1234 and so on ...

I'll probably use Ajax Comments soon to avoid the page reload. Any ideas what I can do in the meantime? Looks like a bug in Drupal to me?

# Answer
I did end up fixing it by using Ajax comments
> 0 votes

---
Tags: 7, comments
---


# Question
Title: Access the label for a form element via hook_form_alter
I have a form with `id` equal to `webform_client_form_3`. I have a particular field that I'm altering by applying a class to it like so:

```
$form['submitted']['estimated_annual_distribution_of_effort']['sensor_technology']['#attributes']['class'][] = 'span1';

```

This all works great. However, I also need to add a class on to the label for that particular element as well. Looking through the `$form` array, I haven't been able to find anything that gives access to the labels. Am I just missing something or are the labels not part of the `$form` array?

# Answer
The attributes for labels are hard-coded into the `theme_form_element_label()` function. You can override it at the theme/module level but you'll have to do so for *all* labels in the system as the variables passed to the theme function do not contain the form context.

The easiest thing to do would be to add a predictable class to each label in every form (based on the name of the form element that the label is for), and then use a CSS selector based on a combination of your form ID and the label class to target it.

Unfortunately there's a fair bit of code you'll need to copy over, and only one small change you'll need to make, but I can't think of another way to do it:

```
function MYTHEME_form_element_label($variables) {
  $element = $variables['element'];
  // This is also used in the installer, pre-database setup.
  $t = get_t();

  // If title and required marker are both empty, output no label.
  if ((!isset($element['#title']) || $element['#title'] === '') && empty($element['#required'])) {
    return '';
  }

  // If the element is required, a required marker is appended to the label.
  $required = !empty($element['#required']) ? theme('form_required_marker', array('element' => $element)) : '';

  $title = filter_xss_admin($element['#title']);

  $attributes = array();
  // Style the label as class option to display inline with the element.
  if ($element['#title_display'] == 'after') {
    $attributes['class'] = 'option';
  }
  // Show label only to screen readers to avoid disruption in visual flows.
  elseif ($element['#title_display'] == 'invisible') {
    $attributes['class'] = 'element-invisible';
  }

  if (!empty($element['#id'])) {
    $attributes['for'] = $element['#id'];
  }

  // NEW CODE HERE
  $label_class = 'label-for-' . $element['#id'];
  $attributes['class'] = isset($attributes['class']) ? $attributes['class'] . ' ' . $label_class : $label_class;

  // The leading whitespace helps visually separate fields from inline labels.
  return ' <label' . drupal_attributes($attributes) . '>' . $t('!title !required', array('!title' => $title, '!required' => $required)) . "</label>\n";
}

```

Once you put that code in your theme's template.php file and clear the cache, you'll be able to target the label with CSS like so:

```
form#webform_client_form_3 label.label-for-edit-field-name

```
> 1 votes

---
Tags: 7, forms, webforms
---


# Question
Title: How to display all product prices on the page at once with Drupal commerce?
I have several products related to a single product display node using Drupal Commerce.

Currently this page only shows a single price (related to the product option currently selected in the dropdown). The only way you can see the prices of the other products is to change the dropdown, which invokes an AJAX request to reload the current product options (including price).

Obviously this is counter-intuitive for customers, who are used to seeing all of the prices available at one time, and not having to change to a new option with the dropdown just to see the price of that option.

How do I change this display so it functions like a traditional e-commerce website? By that I mean either a dropdown that contains the product name AND product price, or (far more preferably) a table with the list of available products, with their prices in one of the columns?

I can only assume that this very basic functionality must exist somewhere in the Commerce configuration settings somewhere, but as yet I haven't been able to find it.

I could easily write a module to code round this problem, but I'm currently evaluating Commerce to see whether it's good enough for our agency to use in future e-commerce projects, *without* having to re-invent the wheel over and over again. To that end, answers involving code probably won't be too useful.

Muchas gracias

# Answer
If themeing is considered "involving code", then you could create a view block.

Using Contextual Filters and Relationships, a View will be able to list all the referenced products on a node (including their fields).

1. Start by creating a View listing all the nodes that have a product reference field (ex: Product Display).
2. Add a Contextual Filter for the Nid that defaults to use the Nid from the URL
3. Next add a Relationship (Product) using the product reference field of the Product Display node
4. Then add another Relationship (Line Item) for the Commerce Line Item of the referenced product

After that is all setup, you can add fields that use the Line Item relationship to get product titles, calculated prices, etc.
> 4 votes

---
Tags: commerce
---


title: Simpletest db table cleanup

text:
# Question
Title: Simpletest db table cleanup
Everytime I run simpletest it creates tables that it does not clean up. Is there anyway to tell drupal to automatically clean these? I looked in my db today and there are hundred of misc unecessary simpletest tables. Thank you

# Answer
That only happens when the test is aborted (e.g. fatal error inside the test class) so that Simpletest isn't able to do the cleanup.

There is a button called "Clean environment" at the bottom of the test overview page and a message telling you about that button when a test is aborted.
> 2 votes

---
Tags: 7, testing
---


title: How do I use hook_theme() in a module?

text:
# Question
Title: How do I use hook_theme() in a module?
I need help in using hook\_theme in my custom module. Any good examples is much appreciated. I have created a CCK input form and I want to theme the input form using hook\_theme. The content type is created using `hook_install()`.

I have used `hook_form_FORM_ID_alter()` to alter the theme of the input form. Following is the code for that.

```
 function footer_menu_form_footer_menu_node_form_alter(&$form,&$form_state,$form_id) {
   theme('footer_menu_node_form', array('form' => $form));
 }

 function footer_menu_theme($existing, $type, $theme, $path) {
   return array('footer_menu_node_form' => array(
     'arguments' => array('form' => NULL),
     'template' => 'footer-menu-node-form',
     'render element'=> 'form',
   ));
 }

```

I have also created a footer-menu-node-form.tpl.php file inside the module, and the following is the code in the template file.

```
 <div id="title"> <?php print drupal_render($form['title']); ?>
 <div id="tree">
 <h2>Menu Tree</h2>
  </div>
 <?php print drupal_render($form['title']); ?>
 // this one is for rendering all the remaining items, like hiddens:
<?php print drupal_render($form); ?>

```

When I load the footer menu content type. The content within the `<h2>` tag is alone printed and then I get the following error:

> Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 40961 bytes)

Can anyone tell me what I doing wrong, or could anyone suggest me an efficient way to use `hook_theme()` in modules?

# Answer
The proper way to assign a theme function to a form using `hook_form_alter()` is like this:

```
function footer_menu_form_footer_menu_node_form_alter(&$form,&$form_state,$form_id){
  $form['#theme'] = 'pz_footer_menu_node_form';
}

```

I can't tell if you're using Drupal 6 or 7; you're using the `arguments` property in your theme declaration which is only valid in Drupal 6, and also the `render element` property which is only valid in Drupal 7.

Judging by the out of memory error I'm guessing Drupal 7. As you call `drupal_render()` on the the `$form` object in your template file, it runs that variable back through the same theme function, and you end up with an infinite loop.

Try changing the last line in your template file to this:

```
<?php print drupal_render_children($form); ?>

```

That should stop the error from happening.
> 2 votes

# Answer
In your theme function definition, you use the "arguments" index, but you should use the "variables" index; then, as reported in hook\_theme(), "variables" and "render element" exclude each other: If you are using one, you should not use the other.

> Each information array must contain **either a 'variables' element or a 'render element' element, but not both**. Use 'render element' if you are theming a single element or element tree composed of elements, such as a form array, a page array, or a single checkbox element. Use 'variables' if your theme implementation is intended to be called directly through theme() and has multiple arguments for the data and style

Using drupal\_render() could cause an infinite loop, but only if `$form`, or one of its sub-elements uses the `#theme` (or `#theme_wrappers`) property, and that property points to a theme function using the same template file that you are showing in your question.

`drupal_render()` calls `theme()`, but only in two cases.

```
  if (isset($elements['#theme'])) {
    $elements['#children'] = theme($elements['#theme'], $elements);
  }

```

```
  if (isset($elements['#theme_wrappers'])) {
    foreach ($elements['#theme_wrappers'] as $theme_wrapper) {
      $elements['#children'] = theme($theme_wrapper, $elements);
    }
  }

```

If `$elements['#theme_wrappers']` and `$elements['#theme_wrappers']` (where `$elements` is the argument passed to `drupal_render()`) are not defined, `drupal_render()` doesn't call `theme()`.
> 1 votes

---
Tags: hooks, theming
---


# Question
Title: How to programmatically create a View on a node that displays SQL Query content?
How can I programmtically create a View on node(s) that displays the content from a specific query?

For example I would like to display the following:

```
$args = array(':nid' => $node->nid);
$results = db_query('SELECT USER_ID FROM USER INNER JOIN node ON USER.OFFICE_ID =
  node.title AND node.nid = :nid', $args);

```

Essentially, I would like to grab the 'nid' from the current node and I would like the View to display all 'users' associated with the current node, as the query would return.

I have been able to achieve this through a custom module. But I have been requested to use Views instead.

EDIT:

I've done what Johnathan Elmore suggested and got the View to display the correct information if I manually enter the 'nid' in the 'Preview with contextual filters:' space. However, if I go to the node itself, it will not display the query content.

For example:

I have nid == 123 with url alias 'office-123', if I enter 123 in 'Preview with contextual filters:', it will display the correct query information. However, if I go to 'mysite/office-123' nothing is displayed.

How can I get this View to display when I go to the node url?

# Answer
> 4 votes
You can create a View block to show on the nodes, and use a contextual filter (Content: Nid) in the View to figure out which node to reference.

Then you can display the related user (user reference field?) for that node in the block.

In case you are using pathauto to auto alias your node URL's, you can setup the Contextual Filter field (Content: Nid) to determine the Nid from the URL:

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


# Question
Title: How do I get a node based on id in custom content type?
I have a custom content type A that has a field for node id which refers to a different content type B. While creating my view for content type A, I want to identify the id in the field entered by the admin and based on the id find out what node of content type B is being referred to and generate a teaser view for B in the View of A. Does anyone have any insight on how to do this? Its more like providing a list of References with links to an Article where Article and References are both different content types.

# Answer
This is exactly what the node references field modules do. For example in your Article content type, you would create a new field 'Related to References' as a node reference field and link it to relevant nodes of the References content type. The field stores the title of the referenced node and its NID which makes it a lot more user-friendly interface than using a nid.

If you're using Drupal 7.x, the current recommendation is to use the Entity Reference module which takes over from the Node Reference module in CCK.

If you're using Drupal 6.x., you want to enable the Node Reference field which is part of the CCK module. This still leaves a migration path to 7.x by upgrading to the 'References' field module, and then migrating your reference fields to Entity Reference fields.
> 3 votes

---
Tags: views, nodes
---


# Question
Title: When I run cron I get deleted nodes created again
I delete **products** and **product displays nodes type** (both powered by commerce module); then all these node are gone.

After this, I run cron and I get all those (deleted) node back in my site.

How can I trace this problem?

# Answer
> 6 votes
Have you used `drupal.org/project/feeds` to import content into your site? In that case perhaps you have configured your feed to make a import every time cron runs? In that case I think you should set Minimum refresh period to none.

Also, here is a thread facing the same problem: Delete feed, ron cron, feed comes back

---
Tags: cron
---


# Question
Title: Could it be that the drupal database doesn't work anymore after using jquery .load()
After using jquery .load() in drupal 7, the database doesn't seem to work
***module***

```
   <script type='text/javascript'>
   function loadPage (id,level) {
   $.ajax({
          beforeSend: function () {
            // here you can do things before the action start
          },
          success: function () {
          $('#contenpage').load(\"$path/pages/page.php\", { 'var': [id,level]})
          }
        });
   }
   </script>

```

I want to use the database in the page "page" and echo the result back.

***page***

```
 $query = db_select('course_function', 'f');
  $query
      ->fields('f', array('id'))
      ->condition('f.chapter_id', $id, '=')
  ;
  $result = $query->execute();
  print_r($result);
  foreach ($result as $res) {
    $id = $res->id;
  }
echo $id;

```

But it does not work - do I need to use the PHP manner?

# Answer
> 2 votes
Most likely that drupal database API is not available in your page.php file because corresponding files are not included in it. What I usually do if I want to do stuff like this, is declaring a menu item:

```
function MYMODULE_menu(){
    $items['path/page'] = array(
        'type' => MENU_NORMAL_ITEM,
        'page callback' => 'your_function_name',
        'title' => 'AJAX: Page callback'
    );
    return $items;
}

```

the code above adds a new page to drupal menu system and makes it available as: http://www.yoursite.com/path/page

and then in your function

```
function your_function_name() {
    $query = db_select('course_function', 'f');
    $query->fields('f', array('id'))
          ->condition('f.chapter_id', $id, '=');
    $result = $query->execute();
    print_r($result);
    foreach ($result as $res) {
        $id = $res->id;
    }
    echo $id;
    //You need to have exit in such callback functions to prevent drupal theme
    //functions from taking over the page processing
    exit;
}

```

Then in your javascript you can approach this page just like this:

```
<script type='text/javascript'>
function loadPage (id,level) {
$.ajax({
      beforeSend: function () {
        // here you can do things before the action start
      },
      success: function () {
          $('#contenpage').load("http://yoursite.com/pages/page", { 'var': [id,level]})
      }
    });
}
</script>

```

---
Tags: ajax, database, javascript
---


# Question
Title: Getting Error 324 (net::ERR_EMPTY_RESPONSE) when saving changes to content/views/modules
For a few weeks now, I've been getting an error when saving certain changes. This error, in Chrome, is

> Error 324 (net::ERR\_EMPTY\_RESPONSE): The server closed the connection without sending any data.

After I click the save button, the page seems to load for a while (10 seconds or more), then directs to that Chrome error page. But, if I reload the page manually, the changes I've added have actually been saved. I've noticed this happening when: adding a new content type, adding a new field, saving changes to a view, disabling or enabling a module, and even clearing the cache.

After some digging, I found out that this error gets posted to Apache's error log every time this happens:

> \[Fri Mar 30 09:27:11 2012\] \[error\] \[client 74.142.25.146\] PHP Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 12893929 bytes) in /var/www/drupal/includes/database.mysqli.inc on line 329, referer: http://mysite.com/admin/content/node-type/typename/fields/field\_looptest/remove
> \[Fri Mar 30 09:27:12 2012\] \[notice\] child pid 17934 exit signal Segmentation fault (11)

I have two sites I work on, one of which is simply a week-old backup version of the other. Interestingly, the error printed to the log for the up-to-date site is slightly different: The file that seems to be generating the error is includes/database.inc, line 225 instead of includes/database.mysqli.inc. In both cases, the line mentioned is simply an escape string function. `mysqli_real_escape_string()` and `db_escape_string()` specifically.

I'm at a loss. The fact that it's a Drupal core file generating the error is bothersome. Does anyone have any idea why this is happening?

# Answer
So, after a few days of trial and error, I managed to fix this problem. (Although I still am not really sure what caused it...)

The fix that I found was to disable modules until the problem disappeared, then to re-enable those modules. That was it. The problem has not resurfaced for the past few weeks.

Now, some details: I first attempted to fix the problem on my "sandbox" server, disabling modules one at a time with the hope that the problem would go away. It did, and I noted which module(s) were the last to be disabled. However, taking that information back to my main site did not help. Instead, I disabled modules in bulk (everything that could be disabled on a first pass; i.e. all modules not required by another module). After a few passes, the problem did indeed disappear. I'm not sure what caused it or why. If my searches while trying to fix it were any indication, nobody else knows either. Just a quirk of Drupal 6 I suppose.
> 1 votes

---
Tags: 6, database, performance
---


# Question
Title: Trouble hooking blocks with theme templates
So I am making blocks and viewing the page source when they're displayed, and for instance one has the id="block-views-first-row-footer-links-block"

so I make templates called the following: none will work(yes I am clearing the cache)...I am using drupal 7.12

block--views-first-row-footer-links.tpl.php

block--first-row-footer-links.tpl.php

block--footer-links.tpl.php

what am I doing wrong here?

# Answer
> 1 votes
There is a easier way to do this using Block theme. But in case you do not want to use it, you can create block template files in the following order.

block--module--delta.tpl.php

block--module.tpl.php

block--region.tpl.php

More information can be found here.

---
Tags: theming, blocks
---


title: Submit form elements as email

text:
# Question
Title: Submit form elements as email
I have a requirement in which the user should not be able to register to site, but only request registration by filling the form (first name, last name, email, company, etc.). The request should go to site admin's e-mail id. Using webform I have created the form, but I am not able to send it as email.

Also the "Per user submission limit" option of webform is decided by the IP address or cookie (for anonymous user), whereas I would like to limit the form submission by the e-mail ids of the submitting users. How can this be done?

# Answer
> 3 votes
With all due respect, I think Webform is the wrong way to approach this. Drupal core can be configured to handle registration in the manner you are requesting with less workload for your site admins (no manual registration of webform data).

1. On `Administration >> Configuration >> People` (admin/config/people/accounts):
    * Set `Who can register accounts?` to `Visitors, but administrator approval is required`
2. As for the fields in the Webform (first name, last name, e-mail, company, etc.), you should create those on the `Administration >> Configuration >> People >> Account settings` page (admin/config/people/accounts/fields) under the `Manage fields` tab. Make sure to mark the fields as required and to display them on the registration form. Note that storing these fields as part of the user account will cause all of this information to be displayed in the user profile. If you need field-level control of the information (to make last name private/hidden, for example), you can use the Field permissions module.
3. *edited per Berdir's comment* By default, Drupal will send an e-mail to the site administrator when an account is registered. If you need a special notification, you can use the core Trigger and Actions modules (or the contributed Rules module) to set up an action (or rule) to e-mail the administrator(s) when a new account is registered and pending approval.

---
Tags: 7, webforms
---


# Question
Title: Best approach for a minimal HTML5 theme for Drupal
Feel like I'm stuck between a rock and a hardplace, I've decide to post.

I'm looking for answers/opinions on getting going on custom Responsive Drupal v7 theme dev using ONLY HTML5/CSS/Less/Responsive with a primary focus on mobile then desktop with a view to it being a MINIMAL design set. I'm not an IT newbie having been in IT since '86 and then earlydays webdev HTML usage since '97, but due to a health/career change I've recently had to 'upskill' again and hence back in IT and focused now purely on D7 by choice. A lot has changed since '97 and early HTML and now I'm wreaking my brains looking at the best approach to contemporary webdev trends (ie Less/HTML5/CSS/SCSS). I don't really want to use 'off the shelf' free D7 themes as I want to be able to theme myself again using the above. I most definately like the idea of HTML5 Boilerplate/360 and the mobile future.

Numerous hours researching online has left me confused (LOL) with all the available Responsive frameworks (CSS: 360 and up, 1140, inuit/Less etc etc).

So my query here is:

* best approach starting grid for webdev on the above technologies at this entry level of learning. (I like building things so I'm keen as an all rounder, as I think I have way long mised the boat on becoming a 'themer' so my interests lay in 'lego' building in Drupal so to speak).
* should I skip early CSS theory and go straight into Less/SCSS? (html5 will be easy to pick up on me thinks).
* which single Responsive model should I pick to start out with then?

FYI, I'm now on a Linux Ubuntu 11.04 LAMP DEVBOX using a range of tools such as Aptana (and comfortable on a pure text editor) having moved over from M$ but I still have 3 other M$ comps due to other multi-media/pro-music interests.

I've been 'hacking' some D7 themes, but feel I can't see to 'wood for trees' when it comes to hacking to vast amount of data in the css files and feel I'm over whelmed in simply wants to create simple, minimal css so much taht it may be just easier starting from scratch.

Any advice to get me going immediately in the right direction would be most helpful. Thanks in advance. Paul, UK

# Answer
> 2 votes
Less or SCSS are not that dissimilar to CSS (since they compile down to CSS anyway), they just have some additional features (such as mixins) and have in some cases a nicer layout. I personally have used scss and Compass to compile my scss, and also for the ability to include resets and things automatically without having to add in your own reset.css file.

In terms of learning Drupal themes, you have a choice, either use something like the omega base theme and subtheme that, or alternatively start from scratch with a clean, empty folder with the following in it:

```
exampletheme/
    css/
    templates/
    js/
    exampletheme.info
    template.php

```

And build up from there. The existing themes, whilst good for some information, are very content-heavy (by virtue of being mature, complex themes). Use a browser such as chrome/firefox with firebug in order to find out what elements are tagged or classed as. The drupal.org theme guide and the specific section on d6 & d7 is quite a good place to start.

As far as grid frameworks, I started using 960 grid as that was something which conceptually struck a chord with me. They all have similar features, though the way they work in practice is different.

# Answer
> 2 votes
Few links for inspiration :

* Best theme for understanding the themeing stuff : zen
    + html5 is in the 7.5 dev version
* Best HTML5 support and a huge effort to "unclutter" the markup : mothership
    + will leave you with a "tabula rasa" - it won't look nice out of box, but the markup will feel better :)
* another interesting approach in the same direction : pony

# Answer
> 0 votes
OK, the thing is that all of that CSS is there for a reason. Drupal has a lot of features, and there is a lot of markup and styles to go along with to work in a generic sense.

If you are new to Drupal, then I think that starting the HTML and CSS from scratch will be a losing battle. You really need to know how Drupal works in order to do this well.

My recommendation is to start out with the Omega basetheme, which is grid based, media-query aware, and has an HTML5 starterkit for subthemes. Subtheme this, and use it as your starting point. Build up your site to have the features you want, and work on theming it. Then once you have a good grasp of things, spend time eliminating the markup from the templates that you find superflous, and then work on the CSS.

# Answer
> 0 votes
I would just add that it might be helpful to build a couple different sites, each with a different subtheme. When you're still in the early stages of learning it's impossible to pick the subtheme that best matches your style because you're still in the process of figuring out what you like. I suppose you could call this the "date around a bit before you settle down" theory.

Since my goal was also a responsive theme, I tried Adaptivetheme and Omega before settling on Adaptivetheme since it has Panels support which I definitely didn't want to write myself.

Also, to experience Drupal in its purest state, you can use Stark (built-in to core, but the core version lacks a responsive design; the contrib version is patched to be responsive).

# Answer
> 0 votes
You might enjoy reading this article (and checking Planet Drupal regularly for articles from many excellent Drupalists): http://www.zivtech.com/blog/responsive-drupal-theme-50-lines-code-or-less

The author describes something very similar to your request. Mobile first, responsive, etc. as a beginning, and has a sandbox project you can check out for details. Bare bones, on which you can add the design you want.

---
Tags: theming
---


# Question
Title: Undefined index $base_path in include(), line 7 of page--front.tpl.php
I receive this error message in my pages; strange enough, it doesn't appear in the front page.

> Notice: Undefined index: $base\_path in include() (line 7 of /home/kinderen/kinderenenislam.nl/sites/all/themes/kei2/page--front.tpl.php).

Where should I include `$base_path`?

# Answer
`$base_path` is a global variable which should definitely be available in your theme's page template files.

I would guess your theme is doing something to remove that var (perhaps in a preprocess function). You can easily solve the problem using one of the following:

1. Using a call to the `base_path()` function instead of `$base_path`.
2. Using `$GLOBALS['base_path'] in place of`$base\_path\`.
3. Adding the line `<?php global $base_path; ?>` to the top of your page template file(s)
> 1 votes

---
Tags: 7
---


# Question
Title: Assign specific template to specific pages
H i I am quite new in Drupal and have been trying to figure out a way to assign a specific template file to some specific pages following the taxonomy like **page--user--edit.tpl.php** works but I don't want to create a single template file for each page I require to change. I have been trying the following code but this doesn't work for me is there any cleaner way to achieve this in drupal 7

```
function phptemplate_preprocess_page(&$vars) {
 if (arg(0) == 'node' && (arg(1) == '10')) {
   $vars['template_files'][] = 'page-sometest';
 }

```

# Answer
See here Drupal 7 Theme Hook Suggestions

For nodes You can use

> `node--[type|nodeid].tpl.php`
>
> `base template: node.tpl.php`
>
> Theme hook suggestions are made based on these factors, listed from the most specific template to the least. Drupal will use the most specific template it finds:
>
> `node--nodeid.tpl.php`
>
> `node--type.tpl.php`
>
> `node.tpl.php`

Also Drupal 6 Template Suggestions

To use same tpl for multiple pages you need to use theme\_preprocess\_node Like

```
function theme_preprocess_node(&$vars, $hook) {
  $node = $vars['node'];
  if(in_array($node->nid), $myuids)
   $vars['template_file'] = 'your_template_file';
}

```
> 10 votes

# Answer
The Drupal way to do this is to create a specific template file for each page. Trying to override the theme system in this manner will create a mess if your site grows larger and becomes more complex.

If you don't want to create a file per page, I would recommend learning how to use the Panels module. It does take some time to learn, but Panels provides an interface that allows you to relatively easily customize the layouts to any node or groups of nodes (content types, etc.) on your site. If you've never used Panels before, I recommend Node One's introduction.
> 1 votes

---
Tags: theming, 7
---


# Question
Title: How can I require multi-user approval for a node?
I have a created a "Team" node type, and I'd like a single user to "invite" people onto the team, but require each team member's approval.

I currently have workflow states of "Approved" and "Unapproved" linked to the "Team" type, and an unlimited "User Reference" field attached to the "Team" type, but I'm not sure how to use Drupal's built-in approval mechanism appropriately. I could create an intermediary node type ("RSVP", maybe) with an "Approved/Unapproved" boolean field (or Workflow status, I suppose) and a "User Reference" with limit 1, and then link the RSVPs to the "team" type., but this seems a little kludgey.

# Answer
Maybe write your own module

#1 push message for each team member

#2 for each member approval check if this it's all, if yes then push invite to new member/user

#2b if new member accept invite then add her/him to the group (you can do it with og API e.g.)

#3 if someone from group disapprove then remove invite from awaiting list

#x you can add some settings page so e.g. if 50% of team members agree with invitation then proceed to #2 and invite new user
> 1 votes

# Answer
Have you looked at Organic Groups? Would require you reworking what you have already done though...
> 0 votes

---
Tags: 7, workflows
---


# Question
Title: Commerce equivalent of Signup, Pay Per Node, etc
I had previously asked for some information about specific e-commerce functions on D6, and was pointed to UberCart, along with Pay Per Node, Signup, and a few other modules. I've just learned that our hosting company has updated their php install so D7 is now supported.

Are there equivalents to those modules for D7? I know Commerce is the big one, but can it do pay-per-node type stuff (to support a print-on-demand fundraiser)?

# Answer
> 2 votes
Here are a few links that might get you started. Drupal commerce is a lot more powerful than Ubercart, because everything is fieldable you should be able to make your event signup product include any fields you wish to collect. I'm not sure what you mean by print-on-demand fundraiser but hopefully this gets you heading in the right direction.

http://vimeo.com/31459435

http://mustardseedmedia.com/podcast/episode51

~Mark

---
Tags: 7, commerce
---


# Question
Title: How I show theme selection page with thumbnails to everyone?
I want to create a menu link for theme selection to users (also for anonymous users). I have installed the Switchtheme module but it shows only theme names; my requirements are to show the theme name with thumbnails, just like we see in "User account -\> edit -\> theme configuration" or with normal theme selection in `admin/build/themes`. So how can I do this?

# Answer
> 0 votes
Go to permissions page `sitename.com/admin/user/permissions`

search for `switch theme` and apply for roles.

Switchtheme Also provides some Blocks see Block configuration page

Thats all.

---
Tags: 6, theming
---


# Question
Title: use taxonomy terms as values for radio buttons by code
I've built a function for select / checkboxes but I can't get it working for radio buttons.

```
/**
 * helper function to get taxonomy term options for select widget
 * @arguments
 * @return array of select options for form
 */
function popover_get_tax_term_options($machine_name){
    //$options = array( '0' => '');

    $vid = taxonomy_vocabulary_machine_name_load($machine_name)->vid;

    $options_source = taxonomy_get_tree($vid);

    foreach($options_source as $item ) {
        $key = $item->tid;
        $value = $item->name;
        $options[$key] = $value;
    }

    return $options;
}

```

Calling this in a form hook works with: ( shows all terms )

```
$form['third']['field_functioncat'] = array(
    '#type' => 'checkboxes',
    '#title' => 'Functiecategorie',
    '#options' => popover_get_tax_term_options('functie_categorie'),
);

```

But when I call it with radio it doesn't work: ( only shows the title with 1 radio button )

```
 $form['third']['field_functioncat'] = array(
    '#type' => 'radio',
    '#title' => 'Functiecategorie',
    '#options' => popover_get_tax_term_options('functie_categorie'),
  );

```

# Answer
Hmm why didn't I see this... I used `radio` instead of `radios`.

Changed the code and now it works:

```
$form['third']['field_functioncat'] = array(
    '#type' => 'radios',
    '#title' => 'Functiecategorie',
    '#options' => popover_get_tax_term_options('functie_categorie'),
  );

```
> 0 votes

# Answer
```
#options

```

values must be in array: http://api.drupal.org/api/drupal/developer!topics!forms\_api\_reference.html/7#options

example:

```
'#options' => array(
            0 => t('None'),
            1 => t('Team'),
            2 => t('Business'),
            3 => t('Talent'),
        ),

```
> 0 votes

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


title: Could not locate PHPMailer library

text:
# Question
Title: Could not locate PHPMailer library
I am running a Drupal 6 site using the SMTP (6.x-1.0-beta5) and the PHPMailer (6.x-2.2) modules for messaging. I configured SMTP and PHP messages, successfully sent and received test messages.
I am using the *Organic Groups* module and trying to utilize the messaging functions in it, for example receiving notifications for administrator users regarding membership approval.

Drupal isn't sending any mail. When I checked the recent log entries, it reports this error.

> Could not locate PHPMailer library

In /admin/messaging/settings I use HTML Mail (PHPMailer) as the default sending method.

Please help me to resolve this issue.

# Answer
> 1 votes
The module relies on the PHPMailer class to send HTML mail. So to send HTML e-mails using Messaging you first need to install PHPMailer.

Check the README.txt file at /messaging/messaging\_phpmailer/ for PHPMailer installation instructions.

---
Tags: 6, emails
---


title: AJAX callback function never called

text:
# Question
Title: AJAX callback function never called
I'm having trouble with something incredibly simple: When I select an element in a multiselect-form element, I want a textfield to become enabled. The problem I'm having is that Drupal never manages to get in the callback-function I specified.

Here I create my multiselect-element:

```
$form['foocat'] = array(
  '#type' => 'fieldset',
  '#title' => t('Manage subcategories'),
  '#prefix' => '<div class="fieldset">',
  '#suffix' => '</div>',
);
$form['foocat']['subcategories'] = array(
  '#type' => 'select',
  '#default_value' => '',
  '#title' => $foocategory,
  '#options' => $options,
  '#ajax' => array(
    'callback' => 'edit_displayname_callback',
    'wrapper' => 'displayname',
  ),
  '#attributes' => array('id' => 'foocats',),
  '#prefix' => '<div class="formselect" id="selectmapcat">',
  '#suffix' => '</div>',
  '#size' => 9,
);

```

A little bit further in the code I create my textfield:

```
$form['foocat']['subcat_displayname'] = array(
  '#type' => 'textfield',
  '#title' => t('Name'),
  '#default_value' => $entity->foocategory,
  '#size' => 25,
  '#maxlength' => 31,
  '#prefix' => '<div class="floater" id="displayname">',
  '#suffix' => '</div>',
  '#disabled' => TRUE,
);

if(!empty($form_state['subcategories'])) {
  $form['foocat']['subcat_displayname']['#disabled'] = FALSE;
  //Code for setting the textfield, dependent on what's been selected in the multiselect
}

```

And this is my callback function:

```
function edit_displayname_callback($form, &$form_state) {
  watchdog("Test", "Testing callback..", array(), WATCHDOG_ALERT);
  return $form['foocat']['subcat_displayname'];
}

```

The callback is never even called, and I have no idea why. I use AJAX in another part of the same form, and there it does work, so I'm guessing it's not a form problem.

Can anyone spot the problem?

# Answer
I guess you are changing the id with `'#attributes' => array('id' => 'foocats',),` And now the callback is not executed because the id is changed.

if you change your code it will work ( tested this in my own install )

```
$form['foocat']['subcategories'] = array(
  '#type' => 'select',
  '#default_value' => '',
  '#title' => $foocategory,
  '#options' => $options,
  '#ajax' => array(
    'callback' => 'edit_displayname_callback',
    'wrapper' => 'displayname',
  ),
  //'#attributes' => array('id' => 'foocats',),
  '#prefix' => '<div class="formselect MY_SPECIAL_JQUERY_SELECTOR" id="selectmapcat">',
  '#suffix' => '</div>',
  '#size' => 9,
);

```
> 2 votes

---
Tags: forms, ajax
---


# Question
Title: Drupal and jQuery Plugins (ie tools) - overlay - mask isn't working - suspect javascript issue
G'day all,

I've implemented the demo available at http://flowplayer.org/tools/demos/overlay/modal-dialog.html in a hook\_menu to test (note that this is the jquery tools plugin, available via the module jquery plugins). Everything works fine with the exception of the mask, I cannot get it to work.

The only difference between the example javascript on the above link and what I'm using is that I had to encapsulate the javascript with the following:

```
(function($){
  $(document).ready(function() {
    <demo javascript code goes here>
  });
})(jQuery);

```

The demo code appears to be using:

```
var triggers = $(".modalInput").overlay({
  // some mask tweaks suitable for modal dialogs
  mask: {
    color: '#ebecff',
    loadSpeed: 200,
    opacity: 0.9
  },
  closeOnClick: false
});

```

Which all makes sense to me and I cannot see why it wouldn't work.

My version of the javascript is (I removed one button): http://pastebin.com/MH6ehmTR My version of the html is: http://pastebin.com/aW6UpFBQ My version of the css is: http://pastebin.com/tUQWDqZp

The html is taken from the generated html by drupal.

The reason why I need this fixed is to disable access to the rest of the page while the dialog box is open (thus becoming modal). The current situation is that a person can interact with the rest of the page while the dialog is open.

FYI the browser is firefox, it works for the demo code, just not for the drupal implemented one. Also the method of getting jQuery tools overlay available is via the jQuery plugins module.

# Answer
> 1 votes
I had a similar problem where the overlay was displayed in IE7, no elements on the page displayed, including close button. All elements were behind the mask. Adding this in the overlay() settings solved the issue:

```
onLoad:  function() {
  this.getOverlay().insertAfter('#exposeMask');
}

```

now the login popup in my site riparotto works fine.

---
Tags: javascript, modal-dialogs
---