This is the web.
This is netrunner.

Using Webform with Ubercart
Written by Anthony   
Tuesday, 22 May 2012 20:04

Using Webform with Ubercart

It might seem a little behind the curve to be working on a project using Drupal 6 & Ubercart, but the fact is that many organisations are quite happy using D6, and Ubercart really is the the ecommerce platform for Drupal 6.

The fun comes when you require something that is not easily handled by Ubercart's myriad menu options and one must delve furtively into its byzantine innards.

Using Webform With Ubercart

The single most useful thing to know with Ubercart is hook_add_to_cart($nid, $qty, $data). This allows one to use another form to collect an order, e.g. a webform, thereby achieving huge flexibility in one's user interface (UI).  You could, of course, use the Form API to build a form to feed Ubercart, but often a client will want editorial control over the words used, or select options implemented in a form and Webform is the best course of action.

When one has implemented a form, you need to tell it to feed its data to Ubercart. You do this with hook_form_alter(&$form, &$form_state, $form_id)

Because the $form_id is passed to this function, you can check it against the form ID of your particular form to make sure you are operating on the right one.

Tip: it can be very useful to set the form_ID as a variable in the variable table via settings.php, and then retrieve that setting with variable_get() as and when needed.

Hook_form_alter will let you specify a submit function for your form, like this:

$form['#submit'][] = 'mymodule_single_donation_submit';

The actual submit handler is where the magic happens:

// make a webform talk to ubercart and put an order into the cart. price value depends on form

function mymodule_single_donation_submit(&$form, &$form_state) {

$tree = $form_state['values']['submitted_tree'];
$nid = variable_get('mymodule_donation_product_nid', '');
$rate = $tree['donation_value'];
$attribute = db_result(db_query("SELECT combination FROM {uc_product_adjustments}

WHERE nid = %d AND model = 'donation-%s'", $nid, $rate));

$data = array(
'webform_sid' => $form_state['values']['details']['sid'],
'attributes' => unserialize($attribute),
);
uc_cart_add_item($nid, 1, $data);
drupal_goto($path = 'cart', $query = NULL, $fragment = NULL, $http_response_code = 302);
}


uc_cart_add_item($nid, 1, $data); is what actually adds the chosen product to the cart, and drupal_goto() redirects the user to the cart, but it could just as easily go to a thank you page or similar. Note that you can pass form data to the order so that you can retrieve it on order completion and build it into your emails, save it to user profiles or whatever you need to do.