You are here

function commerce_addressbook_saved_addresses_validate in Commerce Addressbook 7.2

Same name and namespace in other branches
  1. 7.3 commerce_addressbook.checkout_pane.inc \commerce_addressbook_saved_addresses_validate()
  2. 7 commerce_addressbook.module \commerce_addressbook_saved_addresses_validate()

Element validate callback: processes input of the address select list.

1 string reference to 'commerce_addressbook_saved_addresses_validate'
commerce_addressbook_form_alter in ./commerce_addressbook.module
Implements hook_form_alter().

File

./commerce_addressbook.module, line 442
Defines addressbook functionality for customer profiles, allowing them to be reused and managed on a per-user basis.

Code

function commerce_addressbook_saved_addresses_validate($element, &$form_state, $form) {
  if (in_array('addressbook', $form_state['triggering_element']['#parents']) && $form_state['triggering_element']['#id'] == $element['#id']) {
    $pane_id = $element['#parents'][0];
    $field_name = variable_get('commerce_' . $pane_id . '_field', '');

    // Load the latest version of the order.
    $order = commerce_order_load($form_state['order']->order_id);
    $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
    if (is_numeric($element['#value'])) {
      global $user;
      $profile = commerce_customer_profile_load($element['#value']);

      // Validate that the user has access to the selected profile.
      if (!commerce_customer_profile_access('view', $profile, $user)) {
        drupal_set_message(t('You must have access to the selected profile.'), 'error');
        return;
      }

      // If we detect a change in the element's value, and the customer profile
      // reference isn't already set to the specified value...
      if ($order_wrapper->{$field_name}
        ->raw() != $element['#value']) {

        // Update the order based on the value and rebuild the form.
        if ($element['#value'] == 0) {
          $order_wrapper->{$field_name} = NULL;
        }
        else {
          $order_wrapper->{$field_name} = $element['#value'];
        }
      }
    }
    else {
      $order_wrapper->{$field_name} = NULL;
    }

    // Save the changed customer profile to the order.
    $order_wrapper
      ->save();
    unset($form_state['input'][$pane_id]);
    $element_key = isset($form[$pane_id]['commerce_customer_address'][$form[$pane_id]['commerce_customer_address']['#language']][0]['element_key']['#value']) ? $form[$pane_id]['commerce_customer_address'][$form[$pane_id]['commerce_customer_address']['#language']][0]['element_key']['#value'] : '';
    if (!empty($element_key)) {
      unset($form_state['addressfield'][$element_key]);
    }
  }
}