2

I am currently working on a Drupal Commerce site that offers highly customizable products with multiple attributes. I am at the stage where i am trying to theme my add to cart form, and am a bit lost.

In my theme, I have created a hook_form_alter, and check for my add to cart form. The $form variable has 2 groups of form fields:

$form['attributes']        // Contains 'Attr_1', and 'Attr_2'.
$form['line_item_fields']  // Contains 'Attr_1_c1', 'Attr_1_c2', 'Attr_2_c1', 'Attr_2_c2'

So each attribute has 2 customization options specific to that attribute. I would like to output my form like so:

Attribute 1: (Select Box)
    Customization 1: (input)   // Attr_1_c1
    Customization 2: (input)   // Attr_1_c2

Attribute 2: (Select Box)
    Customization 1: (input)   // Attr_2_c1
    Customization 2: (input)   // Attr_2_c2

Thus grouping the proper customization line_item_fields with the proper attributes. However, since attributes are already grouped in the $form variable, and are separate from the line_item_fields, I am not sure how to do this. Any thoughts on the best way to proceed?

3

You may find it easier to organize the form elements in a form template.

e.g

/**
 * Implements hook_form_FORM_ID_alter().
 */
function MYMODULE_form_commerce_cart_add_to_cart_form_alter(&$form, &$form_state{
  $form['#theme'] = array('commerce_add_to_cart_form');
}

/**
 * Implements hook_theme().
 */
function MYMODULE_theme($existing, $type, $theme, $path){
  return array(
    'commerce_add_to_cart_form' => array(
      'render element' => 'form',
      'template' => 'form--commerce_add_to_cart',
      'path' => $path . '/templates',
    ),
  );
}

Then you can use a file in

MYTHEME/templates/form--commerce_add_to_cart.tpl.php

and in the template file

print drupal_render($form['element_name']);
// or
print drupal_render_children($form['element_name']);

to specify exactly where to render each form element.

  • Thank you for the tip. Looks like I have been theming my forms the hard way all this time. This seems a much more reliable way of doing things (rather than sticking in open and close divs, etc.. in the #prefix and #suffix in hook_form_alter). This worked great! I would just add to this that you need to do a "print drupal_render_children($form);" after you output all of your elements for a drupal commerce form, as there are a bunch of hidden fields, etc.. that need to be dumped. – MarkD Jan 1 '14 at 20:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.