Skip to main content

How to form alter Ubercart 3 Address Pane Fields

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.

  1. /**
  2.  * Implements hook_element_info_alter().
  3.  */
  4. function MYTHEME_element_info_alter(&$type){
  5.   array_push($type['uc_address']['#process'], 'MYTHEME_process_address_field');
  6. }
  7.  
  8. /**
  9.  * Function to alter the elements of the uc_address field type.
  10.  */
  11. function MYTHEME_process_address_field($element, $form_state){
  12.   // Get the taxonomy terms from the database.
  13.   $locations = taxonomy_get_tree(2);
  14.  
  15.   // Setup our default option.
  16.   $options = array('' => t('Please select your location'));
  17.  
  18.   // Build our options from the terms.
  19.   foreach ($locations as $term) {
  20.     $options[$term->name] = $term->name;
  21.   }
  22.  
  23.   // Alter the billing_company field into a select option.
  24.   $element['billing_company']['#type'] = 'select';
  25.   $element['billing_company']['#multiple'] = FALSE;
  26.   $element['billing_company']['#size'] = 1;
  27.   $element['billing_company']['#options'] = $options;
  28.  
  29.   return $element;
  30. }

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.


Comments