You are here

function commerce_shipping_form_commerce_checkout_form_alter in Commerce Shipping 7.2

Implements hook_form_FORM_ID_alter().

File

./commerce_shipping.module, line 1090
Defines a system for calculating shipping costs associated with an order.

Code

function commerce_shipping_form_commerce_checkout_form_alter(&$form, &$form_state) {

  // Attach the JavaScript to the page to recalculate services if it is enabled
  // for this form. We do this in a form alter instead of the checkout pane's
  // form callback to ensure the whole initial form has been built.
  if (commerce_shipping_recalculate_services($form)) {

    // Build an array to limit validation errors to customer profile data and
    // the currently selected shipping service.
    $limit_validation = array(
      array(
        'commerce_shipping',
        'shipping_service',
      ),
      array(
        'commerce_shipping',
        'service_details',
      ),
    );
    foreach (commerce_customer_profile_types() as $type => $profile_type) {
      $limit_validation[] = array(
        'customer_profile_' . $type,
      );
    }

    // Add a hidden submit button to the page that we'll use to recalculate
    // shipping when the form is updated or a non-JS customer clicks the button.
    $form['commerce_shipping']['recalculate'] = array(
      '#type' => 'submit',
      '#value' => t('Recalculate shipping'),
      '#limit_validation_errors' => $limit_validation,
      '#validate' => array(
        'commerce_shipping_recalculate_services_validate',
      ),
      '#submit' => array(
        'commerce_shipping_recalculate_services_submit',
      ),
      '#weight' => -10,
      '#ajax' => array(
        'callback' => 'commerce_shipping_recalculate_services_refresh',
        'wrapper' => 'commerce-shipping-service-ajax-wrapper',
        'event' => 'click',
      ),
      '#attached' => array(
        'js' => array(
          drupal_get_path('module', 'commerce_shipping') . '/js/commerce_shipping.js',
        ),
      ),
    );

    // Hide the recalculation button via JavaScript if there are shipping rate
    // options or if there aren't any options and shipping service selection is
    // required for checkout.
    if (!empty($form['commerce_shipping']['shipping_rates']['#value']) || !variable_get('commerce_shipping_pane_require_service', FALSE)) {
      $form['commerce_shipping']['recalculate']['#states'] = array(
        'invisible' => array(
          ':input[id^="edit-commerce-shipping-recalculate"]' => array(
            'value' => t('Recalculate shipping'),
          ),
        ),
      );
    }
  }
}