title: Drupal - Shared Backend

text:
# Question
Title: Drupal - Shared Backend
How can I, in Drupal, install a project that have 2 different websites(frontend) but share the same backend? Is it possible?

# Answer
> 3 votes
Simple answer is **YES**. What you are trying to do can be achieved by using one of these modules:

1. The Multi Site installation module (It requires separate database for each site or common database with table prefix.)
2. The Domain Access module

These are just general suggestions, as there are several ways to achieve your goal. You have to choose the right method suited for your needs. This is a screen-cast which would be helpful for you.

# Answer
> 1 votes
You should probably look at the Domain Access module.

> The Domain Access project is a suite of modules that provide tools for running a group of affiliated sites from one Drupal installation and a single shared database. The module allows you to share users, content, and configurations across a group of sites.
>
> ### Technical background
>
> The module uses Drupal's Node Access system to determine what content is available on each site in the network. Unlike other multi-domain modules for Drupal, the Domain Access module determines user access based on the active domain that the user is viewing, rather than which group or site the user belongs to. For more information about Node Access in Drupal, see http://api.drupal.org/api/group/node\_access/7.

---
Tags: iis
---


title: node_save does not save language

text:
# Question
Title: node_save does not save language
I cannot programmatically create a node in anything other than `en` language.

My site has 3 languages:

* en
* fr
* de

And the code for creating a node is:

```
define('DRUPAL_ROOT', ...);
require_once DRUPAL_ROOT . 'includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

$node = new stdClass();
$node->type = "foobar";
node_object_prepare($node);
$node->title = 'test title';
$node->uid = 1;
$node->language = 'fr'; // *** this doesn't seem to work

if ($node = node_submit($node)) {
  node_save($node);
}

```

No matter what I type in the `$node->language = '...';` the result is always the same. The node is created in the English language. I confirm that via looking at `admin/content`.

I've even tried stuffing this variable with a proper language object which I got out of the enabled languages of my site:

```
$languages = language_list('enabled');
$lang = $languages[1]['de'];
$node->language = $lang;

```

# Answer
The behavior was an unfortunate side-effect of the `admin_language` module and the setting `Force use of default language`.

The "offending" code is at http://drupalcode.org/project/admin\_language.git/blob/0167e36c45661502ee6907a5b2b7cad8538b19cf:/admin\_language.module#l112

Disabling this options solves the issue.
> 2 votes

# Answer
Some of the hooks might not be firing, instead of `node_save($node)`, try `drupal_execute($form_id, $form_state)`

That last link was bad... lullabot's should help:

http://www.lullabot.com/articles/quick-and-dirty-cck-imports

doh... drupal 7. Looks like they have changed it to `drupal_form_submit`

http://www.lukaswhite.com/blog/post/2011/drupal-7-drupal\_execute-has-gone-say-hello-to-drupal\_form\_submit
> -1 votes

---
Tags: 7, nodes
---


# Question
Title: Is it possible to access the `session` table using db_query/db_update/db_insert?
is there a security feature that is preventing me from doing anything with `sessions`?

I'm pretty sure this is a bad idea, but I'm switching users around after login.

User A logins in using their credentials, but we switch them to be User B.

Perhaps there's a better way to do this and I don't need to directly change `sessions` at all.

# Answer
> 2 votes
Yes, it's a bad idea :)

No, there are no extra security measures in place that would stop you having access to the `sessions` table (certainly nothing that Drupal is imposing, and if your site is working then Drupal must be able to read/write to that table).

If you want to switch users programatically I can't think of a better way than how the Devel module does it:

```
function devel_switch_user($name = NULL) {
  global $user;

  if ($user->uid) {
    module_invoke_all('user_logout', $user);
  }
  if (isset($name) && $account = user_load_by_name($name)) {
    $old_uid = $user->uid;
    $user = $account;
    $user->timestamp = time() - 9999;
    if (!$old_uid) {
      // Switch from anonymous to authorized.
      drupal_session_regenerate();
    }
    $edit = array();
    user_module_invoke('login', $edit, $user);
  }
  elseif ($user->uid) {
    session_destroy();
  }
  drupal_goto();
}

```

Even if you don't have devel installed (which obviously you shouldn't on a production server anyway), just make a copy of the function in a custom module and tweak it to your needs.

---
Tags: 7, database, sessions
---


# Question
Title: Views 2: Combine two multi-value fields per row
Creating a content type on D6 about short-listed books for a competition. Each entry (book) in the short-list is a node, with fields for book-title, book-description, author-names (multi-value), author images (multi-value).

So in order to create the short-list I'm using views. I thought I could combine multi-value fields using Views 2 but I can't work out how. I wanted to show:

* Book title
* Book description
* Author photo 1 \[image\]
* Author name 1 \[caption\]
* Author photo 2 \[image\]
* Author name 2 \[caption\]
* ...

etc

How can I achieve this using Views 2 on D6?

# Answer
Ah. I gotcha now. Drupal has no internal automagic way of knowing any connection between your author name and photo fields. But, for display purposes at least, you can show them together by hacking at the CCK field template.

If you go into CCK module's directory, you will find a `content-field.tpl.php` file. Copy it into your theme's directory and then COPY it to `content-field-field_author_photo.tpl.php`, eg, based upon the field name of your author's photo field name. It is imperative that you COPY it, not just rename it, CCK needs both the base template and the specific field one.

By default, this bad boy looks like this:

```
<?php if (!$field_empty) : ?>
<div class="field field-type-<?php print $field_type_css ?> field-<?php print $field_name_css ?>">
  <?php if ($label_display == 'above') : ?>
    <div class="field-label"><?php print t($label) ?>: </div>
  <?php endif;?>
  <div class="field-items">
    <?php $count = 1;
    foreach ($items as $delta => $item) :
      if (!$item['empty']) : ?>
        <div class="field-item <?php print ($count % 2 ? 'odd' : 'even') ?>">
          <?php if ($label_display == 'inline') { ?>
            <div class="field-label-inline<?php print($delta ? '' : '-first')?>">
              <?php print t($label) ?>: </div>
          <?php } ?>
          <?php print $item['view'] ?>
        </div>
      <?php $count++;
      endif;
    endforeach;?>
  </div>
</div>
<?php endif; ?>

```

and basically it wraps a CCK content field with lots of CSSable divs and so forth. What you want to do is print out the author name under each photo, so you could do that by replacing the `print $item['view']` (which is your photo) with something along the lines of this:

```
          <?php print $item['view']; ?>
          <?php if (!empty($node->field_author_name[$delta]['value']): ?>
             <div class="author-photo-caption">
               <?php print check_plain($node->field_author_name[$delta]['value']); ?>
             </div>
          <?php endif; ?>

```

And now when CCK builds this field, it will also grab the author name and put it under the photo. It will of course still build the author name field and display it, so if that's not what you want, you can go in the Display Fields section of the node type config and exclude it from the $content variable and then it will only show up here.

Clear caches/theme registry and style up the author-photo-caption class and you should be set. And now wherever this field is displayed, it will grab its counterpart (assuming no typos above :)

(Other assumptions: `field_author_photo` and `field_author_name` are the names of your fields on your system.)
> 1 votes

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


# Question
Title: Is there any way to set a node to be shown in 2 menus?
I have a node **"my-node"** which I set to be shown in the **Main Menu** so far so good.

I created another menu: "My Menu".

Is there any way to show **my-node** in both menu: **Main Menu** and **My Menu**

If I edit the node and go under Menu settings it allows me to choose **just 1 Parent item**

# Answer
Use the Multiple Node Menu module

> This module modifies the "Menu settings" in standard node editing form to allow managing multiple menu links to a node.
> 2 votes

---
Tags: routes
---


# Question
Title: form-state has values from former ajax lookup in validation and submit function
I have a form where many things happen per ajax request as e.g. a lookup of field values which will be pre-filled on button click

Most of the things work fine but there is one problem when submitting/validating the form. The values which were pre-filled in Step-1 supersede input which was made later in the form.

Here is the code for one of my ajax callbacks and the submit and validation functions:

```
function _presence_callback($form, &$form_state) {
  if (isset($_POST['ajax_html_ids'])) {
    unset($_POST['ajax_html_ids']);
  }
  //list($form, $form_state) = ajax_get_form();
  drupal_process_form($form['#form_id'], $form, $form_state);

  $commands = array();
  // show invitees section on certain choices in presence field
  $presence = $form_state['input']['field_attendee']['und'][0]['field_presence']['und'];
  $commands[] = ajax_command_replace("#field_evening_div", render($form['field_attendee']['und'][0]['field_evening']));
  if ($presence !== false) {
    if ($presence === "0") {
      $commands[] = ajax_command_css("#invitees_intro_1", array('display' => 'block'));
    } ...
  }
  $page = array('#type' => 'ajax', '#commands' => $commands);
  return $page;
}

/*
 * Code shall be different from default value
 */
function _validate_registration($form, $form_state) {
  $code = $form_state['input']['field_code']['und'][0]['value'];
  $invitations = views_get_view_result('invitations', 'page', $code);
  if (!$invitations) {
    form_set_error('field_code', t('No valid code'));
    return false;
  }
  $registrations = views_get_view_result('invitations', 'page_1', $code);
  if ($registrations) {
    form_set_error('field_code', t('Code already in use'));
    return false;
  }
  return true;
}

function registration_node_form_submit($form, &$form_state) {
  foreach ($form_state['values']['field_invitee']['und'] as $key=>$el) {
    if (is_numeric($key)) {
        // copy values from one person to some others
    }
  }
}

```

and here is the form alter function

```
function vjoonity_code_form_alter(&$form, &$form_state, $form_id) {
  $form['#validate'][] = '_validate_registration';

  // empty default values without code submission
  $first_name = ... = '';

  $values_exist = array_key_exists('values', $form_state);
  if ($values_exist) {
    // take actions on values from ajax lookups
  }
  // values from ajax lookup for pre-filling the attendee form
  if ($values_exist &&  $code_exists) {
    $salutation = $invitation->field_field_salutation[0]['raw']['value'];
    $title = $invitation->field_field_title[0]['raw']['safe_value'];
    ...
    ...
  }

  // button triggering ajax lookup
  $form['lookup'] = array(
    '#type' => 'button',
    '#value' => t('Go!'),
    '#weight' => 5,
    '#executes_submit_callback' => false,
    '#element_validate' => array('_validate_registration'),
    "#limit_validation_errors" => array(),
    '#ajax' => array(
      'callback' => '_check_callback',
      'wrapper' => array(
        'field_salutation_div',
        'field_title_div',
        ...
        ...
        'code_div',
      ),
      'method' => 'replace',
      'effect' => 'fade',
    )
  );

  // wrappers for ajax around the attendee fields
  if (true) {
    $form['field_attendee']['und'][0]['field_salutation']['#prefix'] = '<div id="field_salutation_div">';
    $form['field_attendee']['und'][0]['field_salutation']['#suffix'] = '</div>';
    ...
  }
  // filling in values from ajax lookup
  if (true) {
    if ($salutation) $form['field_attendee']['und'][0]['field_salutation']['und']['#value'] = array($salutation);
    if ($title) $form['field_attendee']['und'][0]['field_title']['und'][0]['value']['#value'] = $title;
    ...
  }

  // ajax for the presence radio group
  $form['field_attendee']['und'][0]['field_presence']['und']['#ajax'] = array (
    'event' => 'click',
    'callback' => '_presence_callback',
    '#executes_submit_callback' => false,
    //'#element_validate' => array('_validate_registration'),
    'wrapper' => array(
        'further_div',
        'field_evening_div',
        'show_invitees_div',
    ),
    'method' => 'replace',
    'effect' => 'fade',
  );

  ....
}

```

My problem is that in form validation and form submission of the whole form the values array still shows values from the ajax callback and take these as actual form values instead of taking changes to the formular into account.

# Answer
I solved it. One problem was using ajax callbacks instead of ajax paths. Though different Callbacks they all redirected to one callback function. With paths it's not a problem.

Secondly the code had a problem with image buttons as ajax-enabled elements. The final submit always thought to be triggered by one of the ajax buttons though it was the submit button just ordinarily.

Thirdly injecting an indicator value in the callback function to the form\_state and then use it in the form function for further decision taking is certainly the more correct way to do it than mis-using the button values in form\_states' values array. These neither aren't very consistent nor persistent.
> 1 votes

---
Tags: forms, ajax
---


# Question
Title: Are there any hooks that get called before modules are loaded?
There are a few user tracking checks I would like to perform before the site main page gets loaded. I don't really want to have to wait for drupal to load all the modules and start running the theme code before I do this.

Are there any hooks that can be overwritten to perform my checks?

# Answer
> 3 votes
I don't recommend using hook\_init() as it doesn't run on cached pages. Try using hook\_boot(). As per the documentation it runs at the beginning of the page request when Drupal is still in the bootstrap. Hope this helps!

---
Tags: 7, hooks
---


title: Append data to all fields of type x

text:
# Question
Title: Append data to all fields of type x
I want to add additional content/code to all existing fields of type x. I'm unsure of what options I have for achieving this. I initially thought that hook\_form\_alter on all \*_node\_forms would be ideal but this won't cover all instances of the field in the form.

Is there a hook I can use to get all instances of a specific field type?

# Answer
> 1 votes
Depending on what you're trying to add/change `hook_field_widget_form_alter()` might be an option. It's invoked whenever a field widget is built and you have access to context data so you can easily determine which field type/entity type/bundle you're dealing with.

```
function hook_field_widget_form_alter(&$element, &$form_state, $context) {
  // Add a css class to widget form elements for all fields of type mytype.
  if ($context['field']['type'] == 'mytype') {
    // Be sure not to overwrite existing attributes.
    $element['#attributes']['class'][] = 'myclass';
  }
}

```

---
Tags: 7, entities
---


# Question
Title: Strange characters after URL -> /#.UAfaBbTY-iE
I'm not sure how it's happened, but on each page there are some characters appended to the URL, similarly to the following one:

They seem to be the same for each page. Anybody know what is causing this?

# Answer
Do you have an AddThis widget on any of the pages? This is a known issue with that widget. to resolve change this portion of the snippet:

```
var addthis_config = {"data_track_addressbar":true};

```

WITH

```
var addthis_config = {"data_track_addressbar":false};

```
> 7 votes

---
Tags: uri
---


# Question
Title: Code for group programatically fields on edit form similar to Flexifield
I am looking how programmatically to group fields on edit form similar to Flexifield. The idea is group in the edit form some fields unlimited. I want to group the fields like as shown in the next link:

http://blog.merge.nl/2009/08/05/multiple-fieldsets-cck-multigroup

I have tried the Flexifield module but has a lot of errors and poor support.

I am working with drupal 6.x.

Thanks very much!!.

# Answer
Have you tried the first link on that page? To the dev version of CCK? I just had to do this very thing this morning. The dev version of CCK has an additional module included with it called multigroup. You create a new field of the multigroup type, then add all the fields you want to include in it. Set the number of repeats on the multigroup to unlimited, and you (or your users) can then add as many groups as necessary.
> 1 votes

---
Tags: 6, entities
---


title: Import js code in node

text:
# Question
Title: Import js code in node
I'm using Drupal 7 and Clean theme. And i have got a map. That's javascript codes. I created map field in my content type and want import this javascript in node.

How can i do?

# Answer
> 0 votes
hook\_node\_view\_alter() will make sure that a node is being prepared for edit before to be rendered for view.

e.g.

```
function MODULE_node_view_alter(&$build){
   $build['mymap'] = array(
       '#markup' => 'Your JS Code',
   );
}

```

# Answer
> 1 votes
Alternatively use hook\_node\_view\_alter() and drupal\_add\_js()

```
drupal_add_js('path/to/file.js', 'file');

```

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


title: drupal_static array losing values

text:
# Question
Title: drupal_static array losing values
I have a module that i created for the sole purpose of integrating it with sitecatalyst. If you are unaware of what sitecatalyst is, it is an api that helps create reports based on statistics of your website. EX: Pageviews, Visitors, etc. Im aware there already is a module for omniture sitecatalyst but is not something i can really use. I need to track many different variables as well as make it track when certain events fire. EX: User Login, Create New Account, Comment Submitted, Search for something, etc. Below i have code that fires everytime in preprocess\_page, whenever a user logs in successfully, the properties i need set, and the setting of a static array with all the values i need to create the javascript code needed in order to track everything correctly.

My problem: I used mymodule\_user\_login and launches as soon as a user logs in successfully. I set all the properties and then set all those variables inside my static array. However, the code in the preprocess\_page gets launched everytime and therefore would overwrite the static array created when the mymodule\_user\_login function was called. Can someone please help me how to figure out how to do this. Ive been racking my brain.

Thank you in advance for any help

```
function mymodule_preprocess_page(&$variables) {
    if (arg(0) == 'admin') {
       return;
    }

    $props = retrieve_props();
    foreach ($props as $key => $data){
        mymodule_set_variable($key.'=', $data);
    }

    //CODE TO CREATE JAVASCRIPT CODE GOES HERE FOR SITE CATALYST
}

function mymodule_user_login(&$edit, &$account) {
    $props = retrieve_props();
    foreach ($props as $key => $data){
        mymodule_set_variable($key.'=', $data);
    }
    mymodule_set_variable('s.events=', 'event13');
}

function retrieve_props(){
    $props = array();

    /*Program Properties*/
    if (isset($_COOKIE['tsource']))
        $tsource = $_COOKIE['tsource'];
    else
        $tsource = 'Organic';
    $props['s.campaign'] = $tsource;

    $server = $_SERVER['COMPUTERNAME'];
    $props['s.server'] = $server;

    $header = drupal_get_http_header();
    if(isset($header['status'])){
        $pageType = 'errorPage';
    }
    else{
        $pageType = null;
    }
    $props['s.pageType'] = $pageType;

    $rel = getNodeRelation();
    $deg_level = null;
    $cat = null;
    $sub_cat = null;

    if (isset($rel['level']))
        $deg_level = $rel['level']['val'];

    if (isset($rel['category']))
        $cat = $rel['category']['val'];

    if (isset($rel['subject']))
        $sub_cat = $rel['subject']['val'];

    $props['s.prop1'] = $deg_level;
    $props['s.prop2'] = $cat;
    $props['s.prop3'] = $sub_cat;

    $schoolName = null;
    $program = null;
    $channel = null;
    $pageType = null;

    if(arg(0) == 'node'){
        $currentURL = drupal_get_path_alias($_GET['q']);
        $arrURL = explode('/',$currentURL);
        $channel = $arrURL[0];

        if ($variables['node']->type == 'school') {
            if (count($arrURL) > 1)
                $schoolName = $arrURL[1];
        }
     }
     else if (arg(0) == 'online-degree'){
         $program = arg(1).'-'.arg(4);
         $pagetype = 'program';
     }
     $props['s.prop4'] = $schoolName;
     $props['s.prop5'] = $program;

     $searchTerm = null;
     if (isset($_GET['textsearch']))
         $searchTerm = $_GET['textsearch'];

     $props['s.prop6'] = $searchTerm;

     return $props;
}

function mymodule_set_variable($name = NULL, $value = NULL) {
  $variables = &drupal_static(__FUNCTION__, array(), FALSE);

  if (empty($name)) {
     return $variables;
  }
  else {
     $variables['variables'][$name] = $value;
  }
}

function mymodule_get_variables() {
  return mymodule_set_variable();
}

```

# Answer
If you look at the code for the form submission handler used for the user login form (user\_login\_submit()), you will notice that it executes the following code.

```
  global $user;
  $user = user_load($form_state['uid']);
  $form_state['redirect'] = 'user/' . $user->uid;

  user_login_finalize($form_state);

```

user\_login\_finalize() is the function that invokes the `hook_user_login()` implementations.

```
  global $user;
  watchdog('user', 'Session opened for %name.', array('%name' => $user->name));
  // Update the user table timestamp noting user has logged in.
  // This is also used to invalidate one-time login links.
  $user->login = REQUEST_TIME;
  db_update('users')
    ->fields(array('login' => $user->login))
    ->condition('uid', $user->uid)
    ->execute();

  // Regenerate the session ID to prevent against session fixation attacks.
  // This is called before hook_user in case one of those functions fails
  // or incorrectly does a redirect which would leave the old session in place.
  drupal_session_regenerate();

  user_module_invoke('login', $edit, $user);

```

Effectively, the user is redirected after `hook_user_login()` is invoked, which means a new page is being served, and Drupal is bootstrapping once again. The content returned from `drupal_static()` is then reset.

The solution is saving the value in a session variable, for example using functions like ctools\_object\_cache\_get(), and ctools\_object\_cache\_set(), which are already available if you are using the Views module on your site, as it requires the Chaos tool suite, on Drupal 7.
> 2 votes

# Answer
static variables will only persist for the length of a page view. if you need something longer than that, you will either need to cache them in the database or use a $\_SESSION variable.
> 0 votes

---
Tags: users, theming
---


title: Drupal Form API Facebook Login

text:
# Question
Title: Drupal Form API Facebook Login
I have Facebook for Drupal installed on my Drupal instance. My application and everything is working fine. I want to make it so one of my custom content types requires Facebook login to submit. Can I do this using the hook\_form\_alter()? This will be for anonymous users. I want them to see the content type (which they can already see) but once they fill in the fields and hit submit the form will require for them to be logged in through Facebook. Should i use that hook or can i accomplish this in another way?

# Answer
I found out that the Drupal for Facebook module has User Management capabilities which allows me to automatically assign a temporary role to any users authenticated via Facebook. I added a role and changed the permissions to allow for the posting of my custom content type. Everything is working now! Hope this helps someone!!
> 0 votes

---
Tags: 7, forms, social-network
---


# Question
Title: Import RSS Feed to a specific taxonomy term
I want to use Feeds (and maybe Feeds Tamper??) to import some RSS feeds.

I want to add a taxonomy to my feeds.

Example : Yahoo Business RSS is tagged with "Business" taxonomy term. Yahoo News RSS is tagged with "News" taxonomy term. Reuters News RSS is tagged with "news" taxonomy term. etc...

How can I add a taxonomy term to my feed import form ?

Thank you,

# Answer
> 2 votes
To use the feeds module you should have a content type set up in which you'll import these items. I believe the tutorial is just saying that you should set up this new vocabulary and then add a term reference to it in your new content type.

In Drupal 7, to make sure you can set up your vocabulary, verify the following

1. When you go to /admin/modules on your site, is the **Taxonomy** module enabled? If not, check it and save the page
2. Once that's done, you should be able to go to admin/structure/taxonomy to add your new vocabulary.

Don't forget that you should then add a term\_reference field in your content type, so you can tag it with those new terms...

Hope that makes sense! Let us know if it worked.

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


title: Change HTML structure of form?

text:
# Question
Title: Change HTML structure of form?
I want to alter the HTML structure for a particular form in my site. Specifically, I want to add some wrapper DIVs around a few sets of form elements. What's the "Drupal 7" way of doing this?

# Answer
You can implement hook\_element\_info\_alter() to change the theme wrappers used by the form fields.

If you look at the code of system\_element\_info(), you will notice the form fields are defined as in the following code.

```
  $types['textfield'] = array(
    '#input' => TRUE,
    '#size' => 60,
    '#maxlength' => 128,
    '#autocomplete_path' => FALSE,
    '#process' => array('ajax_process_form'),
    '#theme' => 'textfield',
    '#theme_wrappers' => array('form_element'),
  );
  $types['machine_name'] = array(
    '#input' => TRUE,
    '#default_value' => NULL,
    '#required' => TRUE,
    '#maxlength' => 64,
    '#size' => 60,
    '#autocomplete_path' => FALSE,
    '#process' => array('form_process_machine_name', 'ajax_process_form'),
    '#element_validate' => array('form_validate_machine_name'),
    '#theme' => 'textfield',
    '#theme_wrappers' => array('form_element'),
  );
  $types['password'] = array(
    '#input' => TRUE,
    '#size' => 60,
    '#maxlength' => 128,
    '#process' => array('ajax_process_form'),
    '#theme' => 'password',
    '#theme_wrappers' => array('form_element'),
  );

```

You can add a new form wrapper, or change the existing one. Suppose, for example, that you want to add a theme wrapper for the textfield form field; you could use code similar to the following one.

```
function mymodule_element_info_alter(&$type) {
  if (isset($type['textfield'])) {
    $type['textfield']['#theme_wrappers'] = array_unshift($type['textfield']['#theme_wrappers'], 'mymodule_textfield_wrapper');
  }
}

```

Your module then should implement the `theme_mymodule_textfield_wrapper()` theme function, and hook\_theme() to declare it. You can use the code of theme\_form\_element() as guideline to write your code. The form element is contained in `$variables['element']`.

Alternatively, if the form fields you want to wrap with additional HTML use all the same theme wrapper, you can override that theme function using hook\_theme\_registry\_alter(). Be careful, as in this case you are also altering every form field using that theme wrapper, including future form fields for which your wrapper could cause issues.
> 3 votes

---
Tags: 7, theming, forms
---


# Question
Title: Reference Based on Two Fields of a Content Type
I have two content types `account` and `device`. `device` has a reference field named `reference_account_number` and it's referencing `account_number` in `account`, but the unique key for `account` is a composite key `account_number` and `environment`.

I used auto node title module to generate the node title based on `account_number` for `account`, and let `reference_account_number` map on to the node title of the `account` nodes. So my problem comes up when I try to do feed import when there are duplicate `account_number` but different `environment`. The `reference_account_number` only map onto the `account` node that has matching node title.

Is there any way to reference another node based on two fields? I was thinking about adding a `environment` field to `device` content type as well

Ideally, I would like this scenario happens when a user creates a new `device` content.

*User enters the `account number` and `environment`, upon completion, user views the content just created, and `reference account number` provides a link to all existing `account` that matches the `account number` user inputted for the `device` content, same thing goes for `environment`*

Thanks

# Answer
> 2 votes
Is there any reason why you could not just reconfigure auto node title to generate a node title based on a composit account number and environment -- say, something like "\[account\_number\] (\[environment\])"? It seems like if you did this, then your reference\_account\_number configuration would remain unchanged, your feeds will not get confused, and users can still add references by typing the account number only thanks to the standard autocomplete feature of node references.

If you did not like the way that "\[account\_number\] (\[environment\])" looks in the output of your site, you could alter the render array, maybe in a hook\_process\_field. For a good description on hooking the Drupal 7 render process, see The Scary Render Array.

---
Tags: entities, nodes
---


title: Webform Protected Downloads

text:
# Question
Title: Webform Protected Downloads
I am trying to figure out how to use this module.

I've downloaded it, installed it, etc. However, when I try to set up a webform, I'm not seeing anywhere where I can upload files and redirect to a link programmatically.

Where do I set this up?

I found this online, but I don't see "protected" anywhere.

> Configurations on my site:
>
> 1. Installed the modules (Webform Protected Downloads, Private Upload)
> 2. Changed 'Default Upload Privacy Setting:' to 'Public' under 'admin/settings/private\_upload'
> 3. Created a Webform \> attached a file
> 4. Under 'File attachments' selected 'Public'
> 5. Enabled 'Protected' under 'Protected Downloads'.
> 6. Enabled 'view uploaded files' permission for anonymous users under 'admin/user/permissions'

# Answer
> 2 votes
The D6 version of the module doesn't support filefield. You must use the drupal upload module. On the node edit form: Attach a file, set it to private. Switch to the tab "Protected downloads" and specify your settings there. If you don't see the tab "Protected downloads" then it might be a bug. Consider opening an issue for this on the issue queue for the module on drupal.org.

---
Tags: 6, webforms
---


title: How to sanitize filename in D6?

text:
# Question
Title: How to sanitize filename in D6?
Is there a native function to sanitize filenames in Drupal 6? Alternatively, does someone have a function they use that they'd like to share?

# Answer
> 3 votes
Well it depends on what you want to allow in your filenames. There is a similar question here where you will find how to sanitize filenames in PHP.

From the above link, I had used following function to sanitize filenames in my one of the modules:

```
function mymodule_sanitize_string($string) {
    $string = htmlentities($string, ENT_QUOTES, 'UTF-8');
    $string = preg_replace('~&([a-z]{1,2})(acute|cedil|circ|grave|lig|orn|ring|slash|th|tilde|uml);~i', '$1', $string);
    $string = html_entity_decode($string, ENT_QUOTES, 'UTF-8');
    $string = preg_replace(array('~[^0-9a-z_-]~i', '~[ ]+~'), ' ', $string);

    return trim($string, ' -');
}

```

If you want to sanitize user input then Drupal has many input filtering functions e.g. check\_plain(), filter\_xss(), check\_url() etc. There is a good tutorial on Drupal security essentials here.

---
Tags: 6, files
---


# Question
Title: D7 Node Field: Create OG Member Checklist in Node Edit Form
I'm using Drupal 7 to create an intranet site. I'm using OG groups to create committee and department pages. I want to create a field in a "Meeting Minute" node type where a list is populated with all group members. The node author could then select whether the committee member was present or absent at a meeting.

I'm able to use an Entity Reference field to select from *all* users on the site, but I want to limit these checkboxes to just group members.

I'm striking out here; any ideas on where to start would be much appreciated.

Using the OG 7.x-1.x branch.

**UPDATE:** I have tried to use the "Entity Reference View Widget" module to accomplish this, but that doesn't seem to work either.

I'm going to try to restate this for clarity — I need a field on a node edit page that allows me to select one or more users who are also members of a group from the organic groups module.

# Answer
> 0 votes
Use hook\_form\_alter to do a entity field query or SQL query to get a list of UIDs that belong to 1 group ... OG may have a function to retrieve that list I dunno.

Once you have a list of UIDs use Devel and `dpm($form);` the form object and you can simply `unset()` the `#options` values for UIDs that dont belong in the OG group. Here's a similar thing I did for limiting to a taxonomy term\_reference field to a given level of a nested taxonomy.

If you're paranoid you can also append your own validator function to the form\_submit function and cross check that valid UIDs (members in the OG group) are being saved .... but I dont usually bother to do that for intranet sites (I have "trusted" users / staff members ... not joe blow public).

Sample code doing basically the same thing for a taxonomy term reference field.

```
/**
 * Implements hook_form_alter().
 */
function eap_student_videos_form_alter(&$form, &$form_state, $form_id) {
    switch ($form_id) {
      // Field specific overrides.
      case 'eap_studentvideos_node_form':
          $form['field_eap_video_country']['#after_build'][] = 'eap_country_term_limit_to_countries';
          break;
    }
}

function _eap_region_tids() {
  return array(24,35,48,8,4);
}

function eap_country_term_limit_to_countries(&$element) {
    $options = $element[LANGUAGE_NONE]['#options'];
    $result = db_query('
        SELECT tth.tid, ttd.name AS term_name
        FROM taxonomy_term_hierarchy tth
        LEFT JOIN taxonomy_term_data ttd ON tth.tid = ttd.tid
        WHERE tth.parent IN  (:tids)
        ORDER BY 2 ASC
    ', array(':tids' => _eap_region_tids()));
    $country_tids = $result->fetchAllAssoc('tid');
    $country_tid_array = array_combine(array_keys($country_tids), array_keys($country_tids));
    $new_options = array_intersect_key($options, $country_tid_array);
    array_walk($new_options, function(&$value, &$key) { $value = str_replace('-','',$value); });
    // array_merge() destroys the array keys.
    $new_options = array('_none' => '- Select a value -') + $new_options;
    $element[LANGUAGE_NONE]['#options'] = $new_options;
    return $element;
}

```

---
Tags: entities, nodes, organic-groups
---


# Question
Title: Best location to keep the javascript files in drupal 7
I am using javascript for some of the html pages. Where should I store the javascript files in my drupal folder.

# Answer
> 3 votes
If it's a theme, and if you are defining scripts in .info file, keep the .js files in scripts folder of your theme folder (e.g sites/all/themes/mytheme/scripts). You don not have to define the whole path. Just enter the relative path to the .info file (scripts/myscript.js) and it will get included in the entire site.

if you are using drupal\_add\_js, in a custom module, the common practice is to keep the file in module's folder. Set it as drupal\_get\_path.

Although it's not recommended, if you are hardcoding the script in html.tpl.php or page.tpl.php folder, I'd place the js file in theme folder and use a drupal\_get\_path to get the actual path.

---
Tags: 7, javascript
---


title: Contact form SOMETIMES doesn't work

text:
# Question
Title: Contact form SOMETIMES doesn't work
I'm using the contact form, smtp module and secureserver as the mail server. When I run tests via the smtp settings page. Everything works as it should. When I use the contact form, SOMETIMES I get an error other times I don't. After reviewing the drupal log as to what the issue might be. I get the 2 following error for the ones that don't mail out. I get this smtp error;

```
Error sending e-mail from *@something.com to *@something.com : The following From address failed: *@something.com

SMTP server error: Sorry, your envelope sender is in my badmailfrom list.

```

and another error which simply states it couldn't send the email. After running some tests and reviewing the mail headers of the emails that did go through. It seems as thou it sends FROM the email address the user is inputting. This to me like the server would deny it because this essentially is a 'spoof'. On the site information email, we are using "info@ourdomain.com". On the smtp settings, we are using a "donotreply@ourdomain.com". I tried a test by changing the dnr email to the info and it still has the intermittent fails.

Update: I've narrowed down the problem to a Godaddy issue. We don't use the 'web' hosting server as our email server. We use their "Email" server which is the "secureserver" most people have problems with in the threads I've read. We ended up switching over to gmail and everything works as it.

@Citricguy: Naw, we aren't blacklisted. It's just that they have several configuration issues with those email servers. To the point that their own techs don't know what they are talking about half the time..

# Answer
> 1 votes
You may have been blacklisted by the server you're try to send mail to. Check this first.

To help from being marked as spam send from an address ending with your domain name.

For example: do-not-reply@example.com or notifications@example.com

Then you can set the "Reply-To" header email address to your users email using hook\_mail().

Something like this maybe?

```
$params['reply-to'] = $user->mail;

function HOOK_mail($key, &$message, $params) {
    switch ($key) {
        case 'your-key-here':
            $message['Reply-To'] = $params['reply-to'];
            $message['subject'] = $params['subject'];
            $message['body'] = $params['body'];
            $message['headers']['Reply-To'] = $params['reply-to'];
            $message['headers']['Return-Path'] = $params['return-path'];
            break;
    }
}

```

It has been forever and a day sense I've looked at this last, but you may want to scope out RFC822.

Note that \['Return-Path'\] is important here as well if you monitor emails for bounces (hard/soft/etc). Where \['Reply-To'\] directs replies, I believe \['Return-Path'\] directs bounces and errors.

---
Tags: 7, emails
---


# Question
Title: Create a simpletest test to add additional form elements using the "Add another item" button
I am trying to create a test case for my custom module using simpletest in Drupal7. I want to create a node. The problem is that the node edit form contains a number of fields which can have multiple values. Addition values are added by clicking on the "Add another item" button, which adds an addition field (nothing fancy here, just the standard Drupal form behavior).

I would like to create a node with two values for email. By default the node form only displays one email field element. To add a second email address I would have to first click the "Add another item" button, and then enter the email address. I am struggling to understand how to recreate this behavior in my test case. Any ideas?

The following is what I have so far:

```
  // Create a namecards_namecard node using the node form.
  public function testNamecardsNamecardCreate() {
    $this->drupalGet('node/add/namecards-namecard');
    // Create node to edit.
    $edit = array();
    // Enter surname
    $edit['title'] = $this->randomName(8);
    // Enter given name.
    $edit["namecards_namecard_given_name[und][0][value]"] = $this->randomName(8);
    // Enter email address.
    $edit["namecards_namecard_email[und][0][value]"] = $this->randomName(8) . '@' . $this->randomName(5) . '.com';
    // Click "add another item" for another email field.
    $this->drupalPostAJAX(NULL, array(), array('namecards_namecard_email_add_more' => 'Add another item'));
    // Enter another email address.
    $edit["namecards_namecard_email[und][1][value]"] = $this->randomName(8) . '@' . $this->randomName(5) . '.com.cn';
    $this->drupalPost('namecards/add_contact', $edit, t('Save'));
    $this->assertText(t('Namecards namecard @title has been created.', array('@title' => $edit['title'])));
    $this->assertText($edit["namecards_namecard_email[und][0][value]"]);
    $this->assertText($edit["namecards_namecard_email[und][1][value]"]);
  }

```

# Answer
The problem was with the drupalPost() method. I managed to solve the problem by changing the first argument to NULL (e.g. `$this->drupalPost(NULL, $edit, t('Save'));`), which sets the target to the current page. Still not sure why this works instead of string denoting the path. Never-the-less it did solve the problem.
> 0 votes

---
Tags: forms, testing
---


# Question
Title: Only show comments in view where the comment author has a specific role
I am trying to make a Drupal View which only shows the comments of users with a certain role. For example I have a node with content\_author who has Role Y. The same user (with Role Y) placed a comment, another user with Role X posted a comment too.

I want to have a view which only displays comments from users with Role X. This does not depend on the user who is logged in, so I cannot use a contextual filter I suppose.

Did anyone manage to do something like this?

# Answer
> 0 votes
I figured out how to do it.

1. Create a view displaying items of type Node.
2. Create a relationship Comment:User
3. Create a filter User: Roles and require Relationship with User (which was created in 2.
4. Specify the roles

You can style the view (and add fields) as you like.

---
Tags: views, comments
---


title: No content type problem

text:
# Question
Title: No content type problem
When I go to node/add. I see the message showing there is no content type: But, when I go to admin/structure/types. I see three content types I have :

What could that be the problem ?
I'm using Drupal 7.14.

# Answer
I found a fix here with the help of Mohini.

I needed only "Add Vehicle" link in the navigation menu. Thus, I added it with the path "node/add/vehicle". Then I disabled "Add content" and all of its sub-links (Article, Basic page and Vehicle).

Now, when I enabled the Vehicle sub-link (I didn't enable the "Add content" back, and I kept the "Add Vehicle" menu I created earlier), I was redirected to node/add/vehicle from node/add. This is exactly what I wanted.
> 1 votes

# Answer
Try these.

1) You may have changed the Navigation block settings:(Administration -\> Structure -\> Blocks -\> 'Navigation'). Configure the 'Navigation' block under 'Content types'.

2) Configure :structure\>menus\>navigation\>listlinks (if you are using Bartik theme).

Reference: http://drupal.org/node/1166416, http://drupal.org/node/1094238
> 2 votes

---
Tags: nodes
---


title: Add comments to custom node

text:
# Question
Title: Add comments to custom node
I have a module which shows content with the page callback. Here is my page callback (just the relevent code):

```
function my_page_callback() {
    $build=array();
    $build[] = array(
        '#theme' => 'my_theme',
        '#marker' => 'foo',
        '#data' => ...,
        '#contextual_links' => ...,
    );
    $comment=comment_node_page_additions(node_load(getTargetNodeId()));
    $build[]=$comment['comment_form'];
    return $build;
}

```

However the function `getTargetNodeId()` retuns a valid id of a node which is generated unter some conditions with this code:

```
$node = new StdClass();
$node->nid=42;
$node->vid=42;
$node->uid=1;
$node->type = 'my_type';
$node->status = 1;
$node->title = "Fresh generated";
$node->content['mapping'] = 4711; // some internal magic
$node->comment='2';
$node->language = LANGUAGE_NONE;
$node->body[$node->language][0]['value'] = "This text should nobody read.";
node_save($node);

```

Even if in the code above the nid and nid are fixed I take care of it the ids are unique.

And here is my code where I render my node:

```
function module_node_view_alter(&$build) {
    if($build['#bundle']=='my_type') {
        $p=my_page_callback;
        $build['body']=$p[0];
    }
}

```

However the the comment header is generated but the input field is missing. What is the problem?

# Answer
If my\_type is a content type defined in the Drupal site, then I would check in admin/structure/types/manage/my\_type/comment/fields that you didn't delete the comment body.

If this is what happened then the node page changes from what shown in the following first screenshot to what shown in the second screenshot.

The screenshots has been taken using the user #1 for my test site, which means what shown happens to every user.

The same thing should happen when the content type has been deleted, or it has never existed on the Drupal site.

There could be other reasons:

* The only input format available in that site is not accessible from the user who is visiting the page your code is outputting. This is not clearly the case if you are using the user #1 to visit the page.
It also means the site doesn't have the default input format, which is not possible to disable from the user interface. It could be the default input format has been deleted from the database; if this is the case, users would have problems also editing nodes, as the input formats used for comments are the same used for nodes, even if a comment for a node using (for example) full HTML could use plain text, or filtered HTML.
* The content type has been created programmatically, in a way that didn't cause hook\_node\_type\_insert() to be invoked. If this is the case, then the Comment module doesn't have the possibility of adding the comment body field, which is done using the following function.

```
function comment_node_type_insert($info) {
  _comment_body_field_create($info);
}

```
> 2 votes

---
Tags: 7, nodes, comments
---


# Question
Title: Specify node.tpl.php file via template.php for a specific node.
I have two content types on my site:

1. NRG Shop display
2. Links

I have created a tpl.php file for NRG Shop Display and want to re-use this template for node 12 on my site. Node 12 is created from the 'Links' content type.

How can I do this?

I have tried the following:

```
function mytheme_preprocess_node ( &$vars ) {
  if ($variables['nid'] == '12') {
    $variables["theme_hook_suggestions"][] = "templates/node--nrg_shop_display.tpl.php";
  }
}

```

However it does not seem to work.

Any pointers?

# Answer
Try:

```
if ($variables['nid'] == '12') {
  $variables["theme_hook_suggestions"][] = "node__nrg_shop_display";
}

```

The templates folder should be checked automatically so you won't need to prepend the path, and you don't need to add `tpl.php` to the end of the string; the above should work for a template file called `node--nrg-shop-display.tpl.php`
> 4 votes

---
Tags: theming
---


# Question
Title: Need help for Drupal 7 Ajax Add more form elements
```
    $form['feedbackmarkup']['feedback']['num_domains'] = array(
    '#type' => 'hidden',
    '#default_value' => 1,
);
       $num = isset($form_state['values']['num_domains']) ? $form_state['values']['num_domains'] : 1;
     for($i = 1; $i <= $num; $i++){
    $form['feedbackmarkup']['feedback']['fname_'.$i] = array(
        '#type' => 'textfield',
        '#size' => 12,
        '#required' => true,
        '#prefix' => '<tr><td>',
        '#suffix' => '</td>',
    );
    }
       $form['add_more'] = array(
        '#type' => 'button',
        '#value' => t('Add More'),
        '#href' => '',
        '#ajax' => array(
           'callback' => 'for($i = 1; $i <= $num; $i++){
    $form['feedbackmarkup']['feedback']['fname_'.$i] = array(
        '#type' => 'textfield',
        '#size' => 12,
        '#required' => true,
        '#prefix' => '<tr><td>',
        '#suffix' => '</td>',
    );',
           'wrapper' => 'feedback_replace',
         ),
       );

```

and In my Ajax callback function

```
  function ajax_example_simplest_callback($form, $form_state) {
         $test = isset($form_state['values']['num_domains']) ? $form_state['values']['num_domains']+1 : 1;
        $form['feedbackmarkup']['feedback']['num_domains']['#value'] = $test;
       drupal_set_message(print_r($form_state['values'],true)); //It is printing form_state with values but not adding my fields above in for loop
        return $form['feedbackmarkup']['feedback'];
}

```

# Answer
> 2 votes
It was not adding my field because `#required` is set to `true`. Now I removed it, and my problem is solved.

# Answer
> 1 votes
Make sure that you passing `$form_state` by reference, like

```
function module_form($form, &$form_state) {
  // CODE HERE
}

```

---
Tags: 7, ajax
---


title: Drupal Display "Master" Error in View

text:
# Question
Title: Drupal Display "Master" Error in View
While I'm creating view displays for three of my content types, created first two and auto previews look fine. When I created the third one, the server kinda went down for a while. So I waited till it comes back online, I'm no longer able to auto preview any of the displays, and I'm getting the following error

* Display "Master" uses fields but there are none defined for it or all are excluded.
* Display "Page" uses fields but there are none defined for it or all are excluded.

Help will be appreciated. Thanks

# Answer
Check to make sure you have at least one field listed under 'Fields.' If you use a display type that requires fields without any being selected you will see the error noted in your question.

If it's bugging out, try to cancel your changes and refresh the page. Add a field, save and see if the preview works again.
> 1 votes

---
Tags: views
---


# Question
Title: How to use current Workflow state as a Panels selection rule
How can I use a nodes current Workflow state as a selection rule in the Panels Page Manager UI?

It does not seem to be available under "Selection rules."

# Answer
> 0 votes
I added a new select list field that would update to match the current workflow state each time the workflow changed. I was able to use this field in panels and could accomplish what I needed.

It's not perfect, but it works.

---
Tags: 7, panels, workflows, chaos-tool-suite
---


title: Automating webforms?

text:
# Question
Title: Automating webforms?
I am making a website for a museum that involves a questionnaire. I made this questionnaire with the webforms module, which in turn sends the answers to another page to be processed. The people at the museum do not know drupal, let alone php. So when they want to add questions to the questionnaire, it has to be done by me. This is because I also need to change the values that are passed on the next page (via the redirect URL in the webforms module).

To automate the process for them (they probably know enough to be able to add new questions), I wanted to know if there is any way to pass on all the answers from the webforms questions, so that they do not have to fiddle with the php? This way, all answers will be sent, regardless of the questions on the webforms. The page that receives the values has been coded so that it takes any amount of URL-parameters; You do not have to find a way to do that.

# Answer
> 1 votes
You could use the Rules module and the Webform Rules integration module to redirect to a generated URL.

You could create a rule that loops over the results building a custom URL string pointing to your processor script, and then redirect to that URL.

As long as the string is less than about 2000 characters you should be in good shape.

You may want to look into the Form API as this would be much cleaner and possibly simpler with a custom submit handler.

If I misunderstood your question I would be happy to try again if you'll clarify.

---
Tags: 7, webforms
---


# Question
Title: Check Billing and shipping info to be the same using Drupal commerce module?
I'm using the drupal commerce module and I also installed the commmerce shipping module. Now in my cart I have the form to enter the Billing and Shipping information. So far so good, but I'd like to have the checkbox option to check something like: "Use the billing information for the shipping information". Then when checked I should be able to submit the form and the validation will skip the shipping information form.

Do I need to installed other modules to do this?

# Answer
> 1 votes
No.

~~I recently added this feature to the commerce shopping module (both 1.x and 2.x branch). It hasn't been widely tested yet though, but I am using it for a production site and haven't seen any problems.~~

It's available for the 1.0 version ~~or the 2.x-dev version~~.

This feature has been moved to Drupal Commerce in the 1.4 release (at the time of writing yet to be released), which means right now it's in Drupal commerce dev release and not in the 2.x-dev release.

The setting can be found under: /admin/commerce/config/checkout/form/pane/customer\_profile\_billing

# Answer
> 0 votes
Probably a better solution now integrated into Commerce itself: http://drupal.org/node/1410022

---
Tags: commerce
---


# Question
Title: Change article Status based on Workflow module
I have Workflow set up properly. But when an article is created, it is set to Published automatically. It doesn't appear to the public though, unless the Workflow status is set to Live.

Is there a way to customize the status to be more specific (e.g. say "Pending Review" when the workflow is in Review status, then say "Published" when workflow is in Live)?

Thanks.

# Answer
First, install the Rules module.

I would highly recommend watching the Rules video series at NodeOne by the incredibly talented Johan Falk.

With the Workflow module and the Rules module installed and configured we can create a rule that automatically publishes (or unpublished) content based on it's current workflow state.

To ensure our content is not published by default, we will need to change a few things. Visit example.com/admin/structure/types (if clean URL's are enabled) and click edit next to the content type you're working with. Scroll to the "publishing options" and uncheck "Published" so new content is not publicly visible by default.

---

---

Next, create a new rule. Available at example.com/admin/config/workflow/rules/reaction/add once the Rules module is installed and enabled.

Configure your new rule to react on the event: "Workflow State Has Changed" and click save.

---

---

Next, add a new condition.

---

---

Choose the "Check workflow transition" condition.

---

---

Configure which transition you wish to react on. For example, if you have created the workflow states "Pending Approval" and "Published" you would choose "Pending Approval" under "Old Workflow State" and "Published" under new workflow state.

---

---

Now we can automatically trigger actions once Rules detects a workflow transition from "Pending approval" to "Published". For example, we can trigger an email to editors, publish a node or just about anything else.

Next we need to add an action.

---

---

There are dozens of built in actions, and you can even add your own. One that you may specifically be looking for though is "Publish content."

---

---

Rules and Workflow work very well together in this sense and will likely be able to do everything you need.

I hope this helps. If I misunderstood your question or if I got too off topic I'll try again. :)
> 5 votes

---
Tags: workflows
---


# Question
Title: Use Regex to insert jQuery querystring before a url anchor
On my page I have some content links that start with '/example/'. I'm using jquery to add a querystring to these links, which is the parent of the currently viewed node. So, the code looks like this:

```
//add parent querystring to subpages
$('a[href^="/example/"]').each(function(index, element) {
  var parentAttr = $(this).attr('href') + '?parent=' + Drupal.settings.nodeinfo.nid;
  $(this).attr('href', parentAttr);
});

```

This works great with one big exception. Some of the links look like this (note the anchor at the end):

```
http://mysite.com/example/subpage#anchor-name

```

So, with my jquery, the resulting link looks like this:

```
http://mysite.com/example/subpage#anchor-name?parent=123

```

When the url is structured this way, the anchor part doesn't actually work (it doesn't jump the user to that section of the page). The querystring actually needs to inject itself between the full url and the anchor. This format is what's needed:

```
http://mysite.com/example/subpage?parent=123#anchor-name

```

How can I modify my code to inject the querystring before the anchor in the url if there is one? I'm assuming it has to be regexed somehow?

# Answer
Rather than writing your own solution you could just a solution that's already tried and tested, like the `parse_url()` function on phpjs.

It works exactly the same way as PHP's `parse_url()` so you can use it to extract all elements of the url, alter what you need, then build it up again.

For example calling the function like this:

```
var components = parse_url('http://username:password@hostname/path?arg=value#anchor');

```

Will yield the following result:

```
{
  scheme: 'http',
  host: 'hostname',
  user: 'username',
  pass: 'password',
  path: '/path',
  query: 'arg=value',
  fragment: 'anchor'
}

```

From there it'll be easy to manipulate the values you're interested in and build up a new URL, without having to resort to a another regex.

Basic example:

```
$('a[href^="/example/"]').each(function(index, element) {
  var components = parse_url($(this).attr('href'));

  var newUrl = components.scheme + '://' + components.hostname + '/' + components.path + '?parent=' + Drupal.settings.nodeinfo.nid + '#' + components.anchor;

  $(this).attr('href', newUrl);
});

```
> 2 votes

---
Tags: javascript
---


title: Site caching a php page?

text:
# Question
Title: Site caching a php page?
I recently 'inherited' a website which has a Drupal installation on it. I know absolutely nothing about Drupal. I don't want to go on for too long, but the site is an absolute mess. It looks like there are two separate websites there that interweave. In all honesty, I dont think I could have paid someone to make a less understandable website. None of the code is documented, there is just no sense to any of it.

Well here's my problem -

I recently changed all of the FTP, SQL and site passwords so the previous ownership couldn't access the site.

On one of the pages there is a PHP script that processes a form. In the form, the php accesses a file called, "login\_credentials.php" (sigh...) which contains the SQL login info.

Now, whenever someone tries to use the page, there is an error that says invalid password on line 12. I, of course, have gone into the login\_credentials.php file and confirmed that the password is the new password.

I also went in and even changed the code so that the SQL connection is on a different line (line 13) but the error still says line 12. This is telling me that the page is somehow cached (maybe?), but I have no idea how.

What's even stranger is that if you are logged into the site as an admin, the error DOES NOT occur. This problem only occurs to the public. (only admins need to log in).

I honestly can't say what the problem is. I'm only moderately savvy when it comes to php/html etc, and know nothing at all about Drupal.

Any ideas?

# Answer
Have you cleared cache yet? If not, go to the URL below to clear the sites cache. See if the error changes like you expected.

* Drupal 6: /admin/settings/performance/drupal
* Drupal 7: /admin/config/development/performance

It could also be that you changed the password of the SQL user that Drupal uses to operate, in which case you would need to update that information in **/sites/yoursite/settings.php**

What version of Drupal are you using?
> 1 votes

---
Tags: caching
---


title: System help not rendering in drupal 7

text:
# Question
Title: System help not rendering in drupal 7
I'm having a problem where my system help block is not properly rendering messages in my main template. It works fine when using my administrative theme, but not in the standard one. When I print\_r my $\_SESSION variable I get the following:

```
[fb_devel] => Array
    (
        [FB_OP_POST_INIT] => 280
    )
[batches] => Array
    (
        [90] => 1
    )
[updates_remaining] => Array
    (
    )
[messages] => Array
    (
        [warning] => Array
            (
                [0] => For easier theme development, the theme registry is being rebuilt on every page request. It is <em>extremely</em> important to <a href="/admin/appearance/settings/cigarnews">turn off this feature</a> on production websites.
            )

    )

```

)

How can I troubleshoot this problem?

# Answer
> 0 votes
Messages are displayed in a block, check that this block is in a region and that region is displayed in your theme.

---
Tags: theming
---


# Question
Title: Get an error message "invalid file extension"
I always get the error message: "Invalid file extension" when I'm trying to upload a PDF file? Does anyone know how to solve that problem?

# Answer
When you create the field file, you need to definy the extention. You have already created the field but you can always modify it. Go on your content type, edit the field file adding pdf on "Allowed file extensions \*"

You can add all the extensions you want. Separate extensions with a space or comma and do not include the leading dot.
> 1 votes

# Answer
In your content type definition, you must define file extensions. Have you added pdf extension?
> 0 votes

---
Tags: files
---


# Question
Title: What bundle and entity_type do I use in field_create_instance to add a field to a taxonomy vocab?
I have a vocab with the machine\_name = the\_bundle. This is my call to field\_create\_instance:

```
field_create_instance(array(
  'field_name' => 'category',
  'label' => 'Some label',
  'required' => true,
  'widget' => array('type' => 'autocomplete_deluxe_taxonomy'), // I've also tried options_buttons
  'entity_type' => 'taxonomy_vocabulary',
  'bundle' => 'the_bundle'
));

```

However when I use the drupal UI to manage the fields on the vocabulary, the instance does not exist. I have verified that the field I'm attempting to create an instance of does in fact exist. I'm also not getting any errors when I enable the module.

What am I doing wrong?

# Answer
The taxonomy module doesn't define any bundle types for `taxonomy_vocabulary` (see `taxonomy_entity_info()`) so Drupal's entity/field system assigns it a default one with the same name as the entity type (`taxonomy_vocabulary`).

```
field_create_instance(array(
  'field_name' => 'category',
  'label' => 'Some label',
  'required' => true,
  'widget' => array('type' => 'autocomplete_deluxe_taxonomy'), // I've also tried options_buttons
  'entity_type' => 'taxonomy_vocabulary',
  'bundle' => 'taxonomy_vocabulary'
));

```

I have to ask though, are you absolutely sure you want to add a field to the vocabulary rather than the term entity? I haven't come across many use cases where adding fields to the vocabulary itself is necessary. Drupal doesn't even have a UI to manage the fields (but I guess that could be why you're going this in code!)
> 2 votes

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


# Question
Title: php code to load latest posts from a term
How can I load 10 latest posts from a term using a PHP code, I know how to display latest titles but I need latest nodes body or teaser too.

How is that possible? (title and body)

# Answer
> 3 votes
One way would be to use `taxonomy_select_nodes()` to build and run the query for you, it orders by `n.sticky DESC, n.created DESC` by default but you can change that to just `n.created DESC` if you need to by passing the 5th argument to the function.

It also limits the query to the number of records found in the `default_nodes_main` variable, which defaults to 10.

```
$tids = array(1); // 1 is the term id (tid)
$result = taxonomy_select_nodes($tids);

while ($row = db_fetch_object($result)) {
  $node = node_load($row->nid);

  $title = $node->title;
  // etc...
}

```

# Answer
> 2 votes
suppose you have $tid with your term id:

for drupal 7:

```
$result = taxonomy_select_nodes($tid, FALSE, "10", array('t.created' => 'DESC'));
$nodes = array();
foreach($result as $node) {
    $nodes[] = $node;
}

```

for drupal 6:

```
$nids = taxonomy_select_nodes(array($tid), 'or', 0, FALSE, 'n.created DESC LIMIT 0,10');
$nodes = array();
while ($n = db_fetch_object($nids)) {
    $nodes[] = node_load($n->nid);
}

```

I didn't test the code above but I'm sure it should work.

---
Tags: 6, theming
---


# Question
Title: Combining Feeds (with teasers) on the homepage?
I want to combine several feeds (several internal blogs from my site and several external feeds) and post them on the homepage. I want to use teasers to only show part of each post.

How should I do this?

I have been trying to use the aggregator module and the feeds\_block that it creates out of all the feeds, however it shows the entire posts. I want teasers.

# Answer
I used the aggregator module and then added the Views block called "feed\_block" on the homepage (and only the homepage). So the blog posts appear just below my introduction to our organization page (that is published to front and stickied).

The aggregator module has all of my external feeds (from other sites). It combines them into a category (I'm not sure if this part is necessary).

The homepage then displays everything from aggregator and also any locally created blog posts (anything with a content-type of "blog").

I might replace this solution with the Feeds module - as the aggregator module does not remove items when the original item is deleted (unless you remove all items and them update them for that feed). Also the feed\_block has a "more" link that is broken. It links to the www.domain.org page, when it should link to the node.
> 0 votes

---
Tags: feeds, nodes
---


# Question
Title: Where to initialize module specific variables
I have been using hook\_init in order to initialize some \_SESSION variables on my application, however a problem I got after... is that hook\_init is called on every ajax request. That's why I wanted to ask, what other hook, function or method should I use in order to initialize my module specific variables. I'm looking for something that's called just the first time the user enters the page, and not when a submit button is launched. (similar to isPostback???).

# Answer
> 2 votes
`hook_init()` is always invoked for not cached pages, even for AJAX request. You can verify the page request is made because an AJAX request, though.

There are two conditions that should be common on any AJAX request:

* The menu path is system/ajax
* The delivery callback is ajax\_deliver()

While the first condition is only true when the form element doesn't set #ajax\['path'\], the second condition should always be true.

Code similar to the following one should detect when a menu callback is called because an AJAX request.

```
if ($router_item = menu_get_item()) {
  if (isset($route_item['delivery_callback']) && $route_item['delivery_callback'] == 'ajax_deliver') {
    // It is an AJAX call.
  }
}

```

In Drupal 6, the menu callback for AJAX/AHAH requests changes, and each menu has its own callback. You can notice the path for those menu callbacks follows a specific pattern: It usually ends with /js, but that is not necessarily true. This means a menu callback could be associated with a path ending with /js, but that menu callback is not for a AJAX/AHAH request.

# Answer
> 1 votes
Quickest way in your `hook_init()` might be to set a semaphore, eg,

```
if (!isset($_SESSION['foo'])) {
  // set your variables here
  $_SESSION['foo']=TRUE;
}

```

would do it for the length of the user's entire session, or,

```
if (isset($_SESSION['foo']) && $_SESSION['foo']!=$_GET['q']) {
  // set your page specific variables here
  $_SESSION['foo']=$_GET['q'];
}

```

the first time the user went to a specific page, and would clear/reset when s/he went to a different page afterwards, etc.

You could also look into

http://api.drupal.org/api/drupal/developer%21hooks%21core.php/function/hook\_user/6

if you wanted to do it just when your user first logs in as well.

---
Tags: hooks, sessions
---


# Question
Title: Show the list of all users who edited a node in Drupal 7
Usually, I display the name of the user edited a node at last, not the ones in the middle. I want to display a list of all the users who edited a node. Is that possible by using Views or any other way? They do so here.

# Answer
> 0 votes
So you thought that part would be closed source ? No! Check http://drupalcode.org/project/drupalorg.git/blob/refs/heads/7.x-3.x:/drupalorg\_handbook/drupalorg\_handbook.module which adds this functionality to book nodes. This module was built for drupal.org but it's not that difficult to get it modified for your needs!

If you want to do this in Views,

1. Create a view with `Content Revisions` in under "Show". uncheck page display,check 'make a block', and click continue and edit. You will be taken to Views UI. Now, remove existing fields and add a new relationship to `Content: Author`.
2. Add new field to user name from the just-added relationship.
3. Add new contextual filter to the node ID. Set the default action to take argument from URL. Then, expand click on Query settings and enable Distinct.
4. Give the block a title and admin name.
5. Place block where you want.
6. Enjoy!

---
Tags: views
---


# Question
Title: How would you incorporate a log out confirmation screen?
Scenario: When users click the "log out" link, I'd like a confirmation form to pop up asking them to click again "yes" to confirm and continue logging out.

Is there module that does this? Or some kind of Rules workflow?

# Answer
**Use jQuery**

Pop-up

```
(function ($, Drupal, window, document, undefined) {

    $(document).ready(function(){
        $('a[href="/user/logout"]').click(function(e){
            if(!confirm("Are you sure you want to log out?")) { e.preventDefault(); }
        });
    });

})(jQuery, Drupal, this, this.document);

```

Or text replace

```
(function ($, Drupal, window, document, undefined) {

    $(document).ready(function(){
        $('a[href="/user/logout"]').click(function() {
            $(this).removeClass('confirm');
            $(this).text("Are you sure?");
            $(this).unbind();
            return false;
        });
    });

})(jQuery, Drupal, this, this.document);

```

---

**Simple Middle Page**

One very simple way to accomplish this would be to create a new page with a simple confirmation message.

For example: `Are you sure you want to <a href='user/logout'>log out</a>?`

Then link to your new page in whichever menu the log out link belongs.

---

**Rules Link**

There is a Rules Link module that can create links with JavaScript confirmations, as well as links that use confirm\_form() You could automatically attach a log out link with confirmation to the User entity.

---

**The l() Function**

You may also be able to implement the () function to generate the link you need.

```
$logout_link = l("Logout", "user/logout", array( 'onclick' => 'return confirm( "Are you sure?" ); ' ) );

```

---

**Form API**

You could use the Form API with a custom submit handler/redirect.

```
$form['logout'] = array(
    '#type' => 'submit',
    '#value' => t('Logout'),
    '#attributes' => array('onclick' => 'if(!confirm("Really Logout?")){return false;}'),
);

```
> 2 votes

# Answer
Depending on how custom you want it, a simple JavaScript popup could work just fine:

```
$('a.logout-link').click(function(e){
  var result = confirm("Are you sure you want to logout?");
  if(!result){
    // Stop the link from working.
    e.preventDefault();
  }
});

```

If you wanted to do something more custom, you could create your own popup and style with CSS. Not sure what your programming level is with Drupal.. But the JavaScript is simple enough :)
> 1 votes

---
Tags: 7, users
---


# Question
Title: Can't get ajax callback and submit from the same form to work
I am building a facebook-like notification system. An icon somewhere in the page that shows you how many notifications you have and if you click on it you get a list of your notifications. Since we wanted a button-like notification icon I decided to go with the form engine.

So I have a form that I render in a Block that does Ajax calls to my server. to check for the number of notifications javascript triggers the jQuery("#edit-update-notifications-button").change(); command.

To get the list users can click the button and a floating will be inserted that shows their notifications.

Yet no ajax call does anything I expect...my submit returns me an error (check at the bottum and my callback returns stuff that does not seem to do anything (a past from firebug is also included at the bottum)

I have no clue what I am doing wrong so I was hoping someone could tell me thank you in advance.

```
  $form['Notifications']['update_notifications_button'] = array(
    '#type' => 'button',
    '#value' => t('Done, now tell us about you.'),
    '#limit_validation_errors' => array(),
    '#name' => 'update_notifications_button',
    '#attributes' => array(
      'style' => 'display: none;',
    ),
    '#ajax' => array (
      'callback' => 'update_processMaker_notifications',
      'event' => 'change',
      'progress' => array(
        'type' => 'none',
      ),
    ),
  );
  $form['Notifications']['notifications_icon'] = array(
    '#type' => 'image_button',
    '#value' => t('Step Notification'),
    '#src' => $image_path . $notifications['notifications_image'],
    '#attributes' => array (
      'class' => array (
          'use-ajax-submit',
      ),
      'onmouseover' => '
        this.src=\''. $image_path . $notifications['notifications_hover_image'] .'\'',
      'onmouseout' => 'this.src=\''. $image_path . $notifications['notifications_image'] .'\'',
    ),
);

```

The callback function looks like this:

```
function update_processMaker_notifications () {
   module_load_include('inc', 'ProcessMaker', 'includes/notifications');

  $notifications = get_notifications_array ();
  $image_path = drupal_get_path('module', 'processMaker') . '/images/';

  $commands = array();

  if ($notfications['numof']) {
    $commands[] = ajax_command_insert ('input[name=notifications_icon]',
      'attr',
         array (
           'src' => $image_path . $notifications['notifications_image'],
           'onmouseover' => 'this.src=\''. $image_path . $notifications['notifications_hover_image'] .'\'',
           'onmouseout' => 'this.src=\''. $image_path . $notifications['notifications_image'] .'\'',
         )
      );
    $commands[] = ajax_command_alert('ewf');
    $commands[] = ajax_command_html (
      '#notifications_image_div',
      '<div class="notifications_number"><p>'. $notifications['numof'] .'</p></div>'
    );

  } else {
    $commands[] = ajax_command_alert('ewf');
    $commands[] = ajax_command_remove ('.notifications_number');
  }

  $drupal_ajax = array ('#type' => 'ajax', '#commands' => $commands);

  //return the form that holds the notification button
  ajax_deliver($drupal_ajax);
}

```

and this is my submit function, that so far only serves testing purposes:

```
/**
 * Submit handler for the ProcessMaker_form().
 */
function processMaker_form_submit($form, &$form_state) {
  // If the user clicked the button, then run the triggersomething trigger.
  if ($form_state['values']['Notifications'] == t('Step Notification')) {
    $commands = array();

    $commands[] = ajax_command_alert('results to show!!');
    //Test if the function is called and works
    $drupal_ajax = array ('#type' => 'ajax', '#commands' => $commands);

    //return the form that holds the notification button
    ajax_deliver($drupal_ajax);
  }
}

```

The submit function returns the following error:

> An AJAX HTTP error occurred. HTTP Result Code: 200 Debugging information follows. Path: /drupal7/ StatusText: OK ResponseText: Welcome to Processmaker | Processmaker @import url("http://localhost/drupal7/modules/system/system.base.css?m7qo3c"); @import url("http://localhost/drupal7/modules/system/system.menus.css?m7qo3c"); @import url("http://localhost/drupal7/modules/system/system.messages.css?m7qo3c"); @import url("http://localhost/drupal7/modules/system/system.theme.css?m7qo3c"); @import url("http://localhost/drupal7/misc/ui/jquery.ui.core.css?m7qo3c"); @import url("http://localhost/drupal7/misc/ui/jquery.ui.theme.css?m7qo3c"); @import url("http://localhost/drupal7/modules/overlay/overlay-parent.css?m7qo3c"); @import url("http://localhost/drupal7/modules/contextual/contextual.css?m7qo3c"); @import url("http://localhost/drupal7/modules/comment/comment.css?m7qo3c"); @import url("http://localhost/drupal7/modules/field/theme/field.css?m7qo3c"); @import url("http://localhost/drupal7/modules/node/node.css?m7qo3c"); @import url("http://localhost/drupal7/modules/search/search.css?m7qo3c"); @import url("http://localhost/drupal7/modules/user/user.css?m7qo3c"); @import url("http://localhost/drupal7/sites/all/modules/ProcessMaker/css/notifications.css?m7qo3c"); @import url("http://localhost/drupal7/modules/shortcut/shortcut.css?m7qo3c"); @import url("http://localhost/drupal7/modules/toolbar/toolbar.css?m7qo3c"); @import url("http://localhost/drupal7/themes/bartik/css/layout.css?m7qo3c"); @import url("http://localhost/drupal7/themes/bartik/css/style.css?m7qo3c"); @import url("http://localhost/drupal7/themes/bartik/css/colors.css?m7qo3c"); @import url("http://localhost/drupal7/themes/bartik/css/print.css?m7qo3c"); Skip to main content Options for the administrative overlayIf you have problems accessing \>administrative pages on this site, disable the overlay on your profile page. \>Dismiss this message. Home Hello drupal Log out Administrative toolbarDashboard (View and customize your dashboard.) Content (Administer content and comments.) Structure (Administer blocks, content types, menus, etc.) Appearance (Select and configure your themes.) People (Manage user accounts, roles, and permissions.) Modules (Extend site functionality.) Configuration (Administer settings.) Reports (View reports, updates, and errors.) Help (Reference for usage, configuration, and modules.) Hide shortcuts
> Add content Find content Edit shortcuts
> Processmaker Main menuHome Secondary menuMy account Log out Configure block Configure block Search form Search Navigation List links Edit menu Configure block Add content Welcome to Processmaker
> No front page content has been created yet.Add new content Configure block Powered by Drupal

And the callback return in firebug looks as follow:

> \[{"command":"settings","settings":{"basePath":"/drupal7/","pathPrefix":"","ajaxPageState":{"theme":"bartik","theme\_token":"p7NYUs8gsoo4ZzTU5Y8f0LSd6wpwhP02tkwBlBLfTsk"},"overlay":{"paths":{"admin":"node/\*/edit\nnode/\*/delete\nnode/\*/revisions\nnode/\*/revisions/\*/revert\nnode/\*/revisions/\*/delete\nnode/add\nnode/add/\*\noverlay/dismiss-message\nuser/\*/shortcuts\nadmin\nadmin/\*\nbatch\ntaxonomy/term/\*/edit\nuser/\*/cancel\nuser/\*/edit\nuser/\*/edit/\*","non\_admin":"admin/structure/block/demo/\*\nadmin/reports/status/php"},"pathPrefixes":\[\],"ajaxCallback":"overlay-ajax"}},"merge":true}\]

# Answer
My suggestion would be to use a slightly more manual approach to this. I would create my own AJAX call:

```
$('#update-notifications-button').click(function(e){
  // Need to display notifications.
  Drupal.notifications.show();
  // Stop button from submitting the regular form.
  e.preventDefault();
});

Drupal.notifications.show=function(){
  // We need to get notifications via AJAX.
  $.ajax({
    type:'GET',
    url: '/notifications/get',
    success:function(html){
      // html should contain all the notifications.
      // put notifications in some wrapper or something...
      $('#notifications-button').after(html);
    }
  });
}

```

Obviously this is all *pseudo-code*. You will need a menu callback for this to work:

```
processMaker_menu(){
  $items['notifcations/get'] = array(
    'page callback' => 'processMaker_getNotifications',
    'etc, etc, etc...',
  );
  return $items;
}

```

And your processMaker\_getNotifications function should print out pure notification HTML and then drupal\_exit().

Ultimately, this would probably be easier to do than messing with the Form API's AJAX. The toughest problems I have ever solved in Drupal have been around the Form API and AJAX..
> 2 votes

---
Tags: 7, ajax, forms
---


# Question
Title: How to redirect a user to the Last Domain Browsed
I have a question, what will i do to save the last domain a user was on either on a cookie or a session or anythin else that will work so that whenever they type the main domain they are redirected to the sub domain they were on last even if the browser is closed. i have about 3 sub domains and the main domain. i am using domain access. for example

main.com \<== TLD sub.main.com \<== Sub Domain 1 sub2.main.com \<== Sub Domain 2

user types in main.com and was browsing sub.main.com yesterday and instantly gets taken to sub.main.com and on another machine user types main.com and gets taken to last domain e.g. sub2.main.com Help!

# Answer
You need to use Cookie as Sessions will be lost once browser is closed. You can use `hook_init()` or `hook_boot()` or `page-front.tpl.php`

```
function hook_init(){
 $domain_last_accessed = $_COOKIE['domain_cookie'];
 if($domain_last_accessed != "" && $domain_last_accessed != $_SERVER['HTTP_HOST']){
 // Check if cookie is set and previous visited was not this domain then redirect
 // redirect using drupal_goto() or Header()
 }
 else{
 // Check for Cookie and set if empty, this might be the first visit or cookie was destroyed
 // SetCookie with $_SERVER["HTTP_HOST"]
 }
}

```

If you want it to be machine independent then you may need to store last accessed domain in DB and note that this will only help authenticated users.
> 1 votes

---
Tags: redirection, domain-access
---


# Question
Title: Seat reservations for (recurring) events on given days
I would like to let my users **reserve *seats*** (or a whole table) for events, and **pay for the reservation via PayPal**.

Different performances/shows would be advertised, users could choose which tables or seats they would like to reserve. A theater OR bar, restaurant, etc. would have "fix" seats and tables, so they would not change (or just rarely); **events can be repetitive/recurring** (e.g. concerts) - in some cases, locations can remain the same too, so only the date changes (e.g. a concert played in Example Bar 3 times a month); but one event can be played in other locations too.

I tried on Drupal.org first, but I got no answer; any help would be appreciated.

If there's no way to "bind" it to Ubercart, I'd solve it in another way (PayPal IPN), but I have to do it ASAP.

P.S.: I've already tried MERCI, Simple Reservation, Hotel Booking System for Ubercart and **Reservation** modules (the latter seemed OK from the picture), but unfortunately I couldn't figure out how to do something similar to what I need - **BUT THIS MEANS NOTHING, maybe I just overlooked some opportunities!**!!

If you say I can solve it with one of these modules, please help! Even if you have a totally different suggestion! Thanks!

---

UPDATE:

In the meantime I found this very interesting article: Ubercart Event Registration
Let me quote from it:

> at the moment, the de facto Ubercart method for doing online event registration is with a module called **UC Node Checkout**. **It's perfect for a one-and-done event registration site, but for a site that is hosting several events simultaneously and on an ongoing basis, it's awkward.** This is due to the fact that it maps a content type to a product SKU - so for each event you'd need to create a new content type. Not really very good long-term, particularly when the site administrator is not overly familiar with Drupal or Ubercart.
>
> So, an alternative solution was devised using the Webforms module. The webform stores the registrant's organization's information - and also asks the registrant how many tickets to the event they want, which is the use case the client specified. The webform, after processing the form, adds the event 'tickets' to the cart. This is done with the 'Webform advanced settings' field in the webform configuration, under 'Additional Processing'.

Good to know. This means the article I found earlier doesn't describe what I need.

Another quote from uc\_event\_registration's readme:

> **UC Node Checkout**
>
> This is the approach that has been used alot for Drupal conferences and demo'd at drupalcons. The huge problem here is twofold: First, registrations are nodes. That means we have to build views to create registration lists and that seems like unnecessary overhead when **Webform is so much lighter weight**. Second, and most importantly, **you need a new content type for EVERY event**. No thanks. On sites that are doing dozens of events per year, this would mean, eventually, a **huge amount of content types**. That's bad.

Here's another one related to Webforms: Drupal Webforms With Dynamic Select Boxes Tutorial This seems very promising, maybe this could be the way one could solve what Andy suggested.
I'm still interested in suggestions for practical solutions - maybe this way!

# Answer
I don't think you are going to find a solution that does 100% of what you need, I expect there will need to be custom development here.

Sounds like a custom content type (CCK) + ubercart + paypal (with ubercart) will be the most flexible solution. Perhaps read through the reservation module to see how it limits the available supply of tickets (i.e. sold out).

I would also suggest to remove the graphical part of the event registation, as this looks like it could be tricky, and instead focus on the *core* functionality of the app, i.e. the registration and payment workflow.

Every problem can be solved in drupal, but some of them are unique, and have their own solution.

If you need this solved ASAP, looks like you may need contractors, or some late nights ;) If you want to attract more quality answers, consider placing a bounty on this
> 2 votes

# Answer
I agree with other answers in that you wouldn't get 100% of the way there without some custom development.

My first thought on solving this is don't worry too much about the interface, just get the data entities right. I think your products really only need two new fields at its most basic (venue, which could be a node reference and date (or another node reference to an event content type and reuse events)). Use stock to be the number of tickets available at a venue for an event and product kit could be a table which is just made up of the individual seats and would therefore manage stock and could also have discounts associated with it.

As far as interface goes you could create a calendar view of "seats" and "tables" (tables are just product kit).

**EDIT**: To distill the gist of the comment thread on this I'm going to summarise here.

What we seem to have got to is the following:

* A particular event at a particular venue is a product class/content type. These content types all have one CCK field, the event date.
* When you create a new instance of this product class you specify the date and add ONE attribute to it, that is the table number. The values of this attribute correspond to the number of tables to the event.

The workflow this describes is that a customer chooses to add an event to the cart, and as part of this process they have to choose a seat number and a number of seats that they want.

This allows a couple of things:

* You can actually price tables differently,
* You can manage stock at a per table level.

This is because an attribute, straight out of the box, has its own SKU and therefore its own stock levels and own pricing. If you think of what attributes are for this makes sense. If you have red and blue shirts you need to know how much of each you have, i.e. stock levels. If large shirts cost more than small shirts then you have to know how to price them.

Keep in mind this only describes the workflow and the backend. Webforms as described in other answers can still be used to control the interface, as could a custom built form. This is just to manage the data entities. You still have to create events manually but I think in this case the small number of content types is a good thing, and a process could be put together pretty quickly to automate some of this (look at Node Import for this, it can with some other contrib modules handle attributes as well if you wanted to customise the values)

Some notes:

An interface that works in this instance is a simple view of your new content types (split them by venue if you want as each content type is venue specific) with a link to the actual product. Then you can select a date and a number of tables. If you want to book seats at different tables then you will need to add another product to the cart.

The module UC Attribute Stock isn't really relevant here I think. As far as I can tell it just combines multiple attributes into one selection. That is given the example above of red and blue colours and small and large sizing, rather than have two dropdowns that the customer has to select from you have one drop down with four selections.

The webform solutions are not precluded from anything above. They are providing the interface, and may make sense if there is other, NON PRODUCT, data that you want to collect from your registration. Keep in mind though that you may be able to collect this from the checkout pane a bit more easily and in line with current shopping workfow. I think writing a form though, especially if you want it to have some smarter widgets on the front of it will be easier and lighter in the long run than shoe horning webform into what you want to do. For the basic workflow I don't think you even need it.
> 2 votes

# Answer
A slightly different approach to the others. You could use Ubercart Event Registration for the individual registration forms, and the custom coding could just be a custom webform widget (see webform\_hooks.php and the files in the *components* directory for more details). This would be responsible for showing only available places, and reserving the selected place on submission. If you saw a reason, you could integrate the component with one of the reservation modules you mention above. I don't think this is much less work than the alternatives, but it's a slightly different model in that it uses webform. (And I agree entirely with Malks that you want to first decide about how it's going to be handled internally.)

**More details**: I think there's a number of ways you can do it, depending on for example whether you want to integrate with an existing module, whether you want to use nodes (can be great for quickly making reports with Views), etc. Here's a very brief description of how you might do it with an entirely bespoke implementation.

Assumptions: a single reservation consists of a date, and any positive number of seat IDs.

1. Create a module that provides a webform component for the reservation.
2. The module should also create a DB table for storing reservation details.
3. To begin with forget about a fancy widget, just make it simple (eg. have a textfield for the date, and another for the seat IDs - they can be entered as a comma separated list at first).
4. On validation, the webform component checks with the DB table that the values are valid (ie not already reserved).
5. On submission, the webform component again checks if the reservation is available, and if so makes the reservation. You want to be careful here that two users submitting a request at the same time can't make the same reservation (eg. use a lock in your submit handler).
6. Go back to your widget and make it fancy, eg. have a nice JS date picker that only shows dates with remaining reservations, maybe with some semi-graphical tables that show available seats and let you select them neatly. But underneath it's all basically doing the same thing.

I've not tried something quite like this, so just an idea!

This is still a very simple system, and as it stands it's not very easy to get the data out. You might want to make some bespoke admin screens or you could views enable your db table.

You don't want to use this approach unless you want the idea of one node per form, with submissions being stored in the webform submitted data table. You really want to be sure that this fits your needs before taking this path imho.
> 1 votes

# Answer
I think you should make table as a product.

We've this relationship: event1 -\> date1 -\> city1 -\> restraunt1 -\> table1

So 1 refers to 1-many relationship.

Have Venue table with information about each venue and tables and other attributes

Have City table with city + venue details

Have OrderBooking table with this: event1,date1,city1,venu-id,product-id

Customer will browse from event to restraunt and will see available seats(products). Write a module to display the (availability) details along with links to create a product. As soon as one clicks a link in the venue, arrange for a pop up which will ask for table specific details and direct to product form and auto populate the product with those details in a custom cck field. Now when tries to buy the product then you should write a module to check availability and after payment have this product related to the OrderBooking table.

You'll need to use UC Node Checkout module as described here for collecting registration data.

I've taken a simplistic view.
> 1 votes

# Answer
I did something similar for a tour agency. I used the Hotel Booking module for Ubercart, each event is a "room" which you can set a limit for occupancy and charge differently depending on the day. On the admin side, you have calendars you can select what days are available on a recurring basis. I believe you can have different kinds of \[events\] as well.

The only issue was it was new in Drupal 7 and had a few bugs, but it may have improved by now.
> 1 votes

# Answer
You can check the following module: Booking Time Slots.

As the name says, it provides Time Slots Booking functionality. It integrates with Views and Calendar.

Check the sample screenshot in Drupal 7.x:

For more, check Comparison of Booking System modules.
> 0 votes

---
Tags: 6, ubercart, entities, payment-gateways
---


# Question
Title: What's the best way to create a booking form?
I need to create a booking form for an event. This form will contain normal text field plus one drop down list with the number of tickets. There will be a prefilled field with the price of the single ticket that user can modify. After the field with the price of the single ticket there will be an other field with the total price of the tickets and when they select the number of the tickets automatically the total price will be updated and stored in the database after the form is submitted. After the submit I need to send an email, I can use mime-mail but let me know if I need to change method due the live field of the prices.

There is not online payment expected.

Let me know if everything is clear.

# Answer
If you're new to Drupal, I would first try the webform module. This is a very popular, well tested module that often gets security fixes which less commonly used modules may not get.

It has all the basic functions you need for creating the options for the form and can easily be configured to send an e-mail upon submission. It will also leave a record of all submitted data in the Drupal database.

To be honest, off the top of my head I'm not sure if webform can do the computation you request or not. However, for that there is the computed field module, which will allow you to write a simple function in PHP to compute the value. Alternately, you could use the rules module's "on node save" event with the action "compute data value" to calculate the total price.

There are a number of other approaches as well but these are commonly used Drupal modules with fairly good documentation and thus are, I think, a good place to start.
> 1 votes

# Answer
I've solved it throught jQuery. I had 3 fields involved. One select, one text field and one text field readonly.

The select defines the number of the tickets, the textfield contains the price of the ticket and the readonly field contains the total price.

I want to update automatically the readyonly field everytime the user changes the select or the textfield with the price. So I did in this way.

```
 jQuery(function(){
function display() {
 var ticket =  jQuery('#ticket').val();
var price =  jQuery('#price').val();
var totalPrice = ticket * price;
jQuery('input[id=totalprice-readonly]').attr(
        {value: totalPrice});
}
jQuery('#ticket').change(display);
display();
jQuery("#price").keyup(function () {
      var price = jQuery(this).val();
 var ticket =  jQuery('#ticket').val();
var totalPrice = ticket * price;
jQuery('input[id=totalprice-readonly]').attr(
        {value: totalPrice});
    }).keyup();

});

```

This is the way how I did. It works properly, it just needs to be completed (thousand separetor and decimal).

All the suggestions are welcome.
> 1 votes

# Answer
Check the Booking Time Slots module, or see Comparison of Booking System modules.

> Module provides Time Slots Booking functionality.
>
> For example:
>
> * Users can go to Calendar and book specified time slots
> * You can configure how many time slots are available and how long are the events, so after that time slot will be released
> * You can configure hourly and half-hourly time lots (in calendar view)
> 0 votes

---
Tags: forms, bookings
---