The Address Field module automatically converts administrative area (i.e., State/Province) abbreviations to full names on node display. I need to do this in my own custom module but can't find the function that the Address Field module uses to do this. How can it be done?
As mentioned earlier, there's no function in addressfield that does this, it's hard coded and not re-usable. Instead, there's a function in addressfield_tokens module which DOES do this.
Using this function isn't really good practice because it's not an official hook (so it could change at anytime without notice), but as long as you're aware of what's going on and you use the proper checks that the module exists, it's the most flexible way to make this happen. Here's how to use it:
First, ensure that addressfield_tokens.module is installed. Then you can use this function from line 338 in the .module file:
You need the $country because abbreviations are sometimes the same for different countries. So, if we wanted to find the full name of California, we would do this:
$california_fullname = _addressfield_tokens_state('US', 'CA') return $california_fullname;
Address field contains a very useful function:
This returns the administrative areas for the country specified, keyed by the abbreviations.
$australian_states = addressfield_get_administrative_areas('AU');
This would result in the following array:
$australian_states = array( 'ACT' => t('Australian Capital Territory'), 'NSW' => t('New South Wales'), 'NT' => t('Northern Territory'), 'QLD' => t('Queensland'), 'SA' => t('South Australia'), 'TAS' => t('Tasmania'), 'VIC' => t('Victoria'), 'WA' => t('Western Australia'), );
I needed to output the Province code as the full Province name as well. I dug into the module and in
addressfield.address_formats.inc I found the following comment:
- render_administrative_area_value: True if the value should be rendered
I also found the following in address.inc:
'#render_option_value' => $address_format['render_administrative_area_value'],
From this, it appears that, if you retrieve the render array for the addressfield for a given entity, you can simply set the
#render_option_value attribute to
TRUE. I did this (code sample below) and, lo and behold, the Addressfield default formatter is observing this attribute nicely. I've got the full province name just as I wanted.
PS: I am making use of entity and uuid_entity modules to store some static content that needs to be version controlled in code and made deployable - thus, instead of
node_load($nid) you see
entity_load_single_by_uuid('node', $somvar['uuid']); in the code sample below.
$node = entity_load_single_by_uuid('node', $somvar['uuid']); $address = field_view_value( 'node', $node, 'field_address_primary', $node->field_address_primary[LANGUAGE_NONE], 'default' ); $address['locality_block']['administrative_area']['#render_option_value'] = TRUE; return render($address);
Hope this proves useful!