How to form alter Ubercart 3 Address Pane Fields

Profile picture for user Phil Frilling
By Phil Frilling, 16 October, 2013
I recently needed to alter the address fields within the Ubercart 3 billing pane. Unfortunately, due to the way Ubercart 3 builds these form elements, the standard hook_form_alter() hook was not going to work. After a few hours of searching I finally discovered this post: https://drupal.org/node/2063949#comment-7750227 With that information I was able to alter my billing pane's company field into a select list taken from a taxonomy. The code below was entered into my theme's template.php file.


/**
 * Implements hook_element_info_alter().
 */
function MYTHEME_element_info_alter(&$type){
  array_push($type['uc_address']['#process'], 'MYTHEME_process_address_field');
}

/**
 * Function to alter the elements of the uc_address field type.
 */
function MYTHEME_process_address_field($element, $form_state){
  // Get the taxonomy terms from the database.
  $locations = taxonomy_get_tree(2);

  // Setup our default option.
  $options = array('' => t('Please select your location'));

  // Build our options from the terms.
  foreach ($locations as $term) {
    $options[$term->name] = $term->name;
  }

  // Alter the billing_company field into a select option.
  $element['billing_company']['#type'] = 'select';
  $element['billing_company']['#multiple'] = FALSE;
  $element['billing_company']['#size'] = 1;
  $element['billing_company']['#options'] = $options;

  return $element;
}
The above code will work for any of the fields provided by Ubercart 3's address panes. All of these options should be available in the $element variable.