You are here

function commerce_product_attributes_add_to_cart_form_attributes_refresh in Commerce Product Attributes 7

Alternative implementation of commerce_cart_add_to_cart_form_attributes_refresh()

We need this because, the given hook (hook_commerce_cart_attributes_refresh) allows you to change each single element. We can't change the $commands, it is to complicated. So we need to hook earlier.

File

./commerce_product_attributes.module, line 112
This module adds some improvements to the Drupal Commerce core.

Code

function commerce_product_attributes_add_to_cart_form_attributes_refresh($form, $form_state) {
  $commands = array();

  // Render the form afresh to capture any changes to the available widgets
  // based on the latest selection.
  $commands[] = ajax_command_replace('.' . drupal_html_class($form['#form_id']), drupal_render($form));

  // Then render and return the various product fields that might need to be
  // updated on the page.
  if (!empty($form_state['context'])) {
    $product = $form_state['default_product'];
    foreach (field_info_instances('commerce_product', $product->type) as $product_field_name => $product_field) {
      $class = drupal_html_class(implode('-', array(
        $form_state['context']['class_prefix'],
        'product',
        $product_field_name,
      )));
      $element = field_view_field('commerce_product', $product, $product_field_name, $form_state['context']['view_mode']);

      // Allow other modules to modify the product output in a
      // refresh context
      $hook = 'attribute_product_field_alter';
      foreach (module_implements($hook) as $module_name) {
        $function = $module_name . '_' . $hook;
        if (function_exists($function)) {
          $function($element, $product, $product_field_name, $form, $form_state);
        }
      }
      $element += array(
        '#prefix' => '<span class="' . $class . '">',
        '#suffix' => '</span>',
      );
      $commands[] = ajax_command_replace('.' . $class, drupal_render($element));
    }
  }

  // Allow other modules to add arbitrary AJAX commands on the refresh.
  drupal_alter('commerce_cart_attributes_refresh', $commands, $form, $form_state);
  return array(
    '#type' => 'ajax',
    '#commands' => $commands,
  );
}