I'm using Drupal 7 with Drupal Commerce and the Commerce Product Option module. Design goal is to have a visual product configurator for choosing custom furniture - an area on the Add To Cart Form where product images update as the user selects individual line item options.

So far I've implemented a semi-successful solution that uses jQuery to (A) modify the line item form to modify the product display area, and (B) add handlers to form elements. This javascript is attached to the form via a custom module, hook_form_alter() and $form['#attached']['js'] which references a javascript file with a defined Drupal.behavior.

(function ($) {
 Drupal.behaviors.prod_form = {
   attach: function (context, settings) {...

The problem I'm having is with the Product Display form, which provides the user a SELECT list (ID=edit-product-id) to choose a specific product from a family of related products (4 seat sofa, 3 seat sofa, loveseat, etc.). Upon initial display everything works, however if the user selects another product the javascript form modifications fail. Looking at the console.log it seems as though the jQuery selectors are failing because they are being called before the form item exists. (no elements are found with selector ...).

I suspect the issue is related to when ajax is called vs. when the elements are being drawn, but stuck on how exactly to resolve. Any pointers or suggestions will be greatly appreciated.

Chris

share|improve this question

1 Answer

Try attaching the JS code using the #after_build function, somthing like this where the module is 'x'.

/**
 * Implementation of hook_form_alter.
 */
function x_form_alter(&$form, &$form_state, $form_id){
    $form['#after_build'][] = 'x_after_build';
}

function x_after_build($form, $form_state){
    if($form['#form_id'] === 'commerce_xyz_form'){
       drupal_add_js(/* ... */);
    }    
}
share|improve this answer

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

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