0

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

1

The CSS id may change on ajax refresh.

E.g edit-product-id, edit-product-id-1

Make sure your js can target the new form markup.

| improve this answer | |
0

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(/* ... */);
    }    
}
| improve this answer | |
0

If you don't want to target every possible id selector the product select list can have, you can add a #process element to the forms product_id field and use inline javascript in the #process function. For example, in your form_alter:

$form['product_id']['#process'][] = 'process_product_id';

Then add the process_product_id function that would look something like this and you can determine the id by using $element['#max_delta']:

function process_product_id($element, &$form_state, $complete_form) {
  drupal_add_js('jQuery(document).ready(function () { jQuery("product_id_' . $element['#max_delta'] . '").{more jquery code here}});', 'inline');
}
| improve this answer | |

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.