You are here

function uc_addresses_select_address in Ubercart Addresses 6.2

Widget for selecting an address.

Parameters

int $uid: The user ID to select addresses for.

string $context: The context in which the addresses are used:

  • checkout_form
  • order_form

string $type: The type of address to select addresses for (shipping or billing).

UcAddressesAddress $default_value: (optional) The option that should be selected.

Return value

array A select form element for selecting addresses.

2 calls to uc_addresses_select_address()
uc_addresses_checkout_pane_address in ./uc_addresses.ubercart.inc
Callback for an address checkout pane.
uc_addresses_form_uc_order_address_book_form_alter in ./uc_addresses.module
Implementation of hook_form_FORM_ID_alter() for form uc_order_address_book_form().

File

./uc_addresses.module, line 1290
Adds user profile address support to Ubercart.

Code

function uc_addresses_select_address($uid, $context = 'default', $type = 'billing', UcAddressesAddress $default_value = NULL) {

  // Get addresses for select.
  $addresses = uc_addresses_get_select_addresses($uid, $context, $type);
  if (count($addresses) < 1) {

    // No addresses found.
    return NULL;
  }

  // Initialize default value, we don't know yet which address in the list is
  // equal to the given default value.
  $address_book_default_value = NULL;
  $options = array(
    '0' => t('Select one...'),
  );
  foreach ($addresses as $address) {
    $data = array();
    $fields = $address
      ->getRawFieldData();

    // Do not include the address ID as that value could change per page load
    // when addresses not coming from the address book can be selected,
    // possible resulting in an illegal choice form error.
    unset($fields['aid']);

    // Replace underscores and spaces with a hyphen.
    foreach ($fields as $fieldname => $value) {
      $fieldname_with_hyphens = str_replace(array(
        '_',
        ' ',
      ), '-', $fieldname);
      $data[$fieldname_with_hyphens] = $value;
    }
    $key = drupal_to_js($data);
    if ($address_name = $address
      ->getName()) {
      $options[$key] = $address_name;
    }
    else {
      $options[$key] = preg_replace('/<.*?>/', ', ', uc_addresses_format_address($address));
    }

    // Check if this address is equal to given default value.
    if ($default_value && !$address_book_default_value) {
      if ($address
        ->compareAddress($default_value)) {

        // Default value found! Save it for later.
        $address_book_default_value = $key;
      }
    }
  }
  $select = array(
    '#type' => 'select',
    '#title' => t('Address book'),
    '#options' => $options,
    '#attributes' => array(
      'onchange' => "uc_addresses_apply_address('" . $type . "', this.value);",
    ),
    '#weight' => -50,
  );

  // Add default value if found.
  if ($address_book_default_value) {
    $select['#default_value'] = $address_book_default_value;
  }
  return $select;
}