03 328 8646

Blog

Creating a Drupal Commerce order form

Note: there's probably a lot more to think through on a site with larger numbers of products, the site we built this for has 3, so we don't have to deal with large forms, big cart updates or paginated views. This site also has Add To Cart Extras enabled, which changes the add to cart form.

Sometimes it would be nice to present your buyers with a view of their cart that both lets them add new products and update existing quantities.

We did this by adding a HOOK_form_alter() to the add to cart form to add the quantities of existing products to the form, and by being careful with what happens to them when the form is submitted - we didn't want to increase the cart contents by the quantities submitted, we wanted them to be set to those values. In this case we opted to wipe the cart contents completely and add the incoming items & quantities as new items rather than updating the existing values. If you can't get all of your items onto a single form then you probably won't want to do this.


function HOOK_form_alter(&$form, &$form_state, $form_id) {

if ('FORM_ID' == $form_id) {
    //Add items in the cart to the add to cart form
    //See if we have a cart
    global $user;
    $prods_in_order = array();
    $order = commerce_cart_order_load($user->uid);
    if (!empty($order)) {

      $o_wrap = entity_metadata_wrapper('commerce_order', $order);

      foreach ($o_wrap->commerce_line_items as $line_item_wrapper) {
        //build a simple array of the items that we have in the cart
        //using prod_id and quantity
        //Ensure we only add product line items
        if ('product' == $line_item_wrapper->type->value()) {
          $prods_in_order[$line_item_wrapper->commerce_product->product_id->value()] = $line_item_wrapper->quantity->value();
        }
      }

      //Feed the order totals into the cart form so they can be updated by the user
      foreach ($form['add_to_cart_quantity'] as $key => $data) {
        if(isset($prods_in_order[$data['#product_id']])) {
          $form['add_to_cart_quantity'][$key]['#default_value'] = $prods_in_order[$data['#product_id']];
        }
      }
      //Ensure we wipe the cart contents before we add
      //The other way around really doesn't work so well
      array_unshift($form['#submit'], 'MY_callback_form_submit');
    }
    //On this site we go directly to the checkout as users can manage
    //Cart contents through the 'order' form
    $form['actions']['submit']['#value'] = 'Checkout';
  }
}

function MY_callback_form_submit($form, &$form_state) {
  //Wipe the existing contents
  //We are then free to add the values sent in the form
  global $user;
  $order = commerce_cart_order_load($user->uid);

  if (!empty($order)) {
   commerce_cart_order_empty($order);
  }

}