You are hereSet the default address on shipping information with smart IP, refresh whole form to have proper counties(administrative area)

Set the default address on shipping information with smart IP, refresh whole form to have proper counties(administrative area)


By Marko Blažeković - Posted on 04 November 2014

The title says it all :) add this to your module, into hook_form_alter and rock

//verify that this is not an ajax request, otherwise country changes will not be able to change the administrative_area information.
//in otherwise, let this section only happen once, and let ajax make changes as expected
if (!(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')) {
if ($form_id == 'commerce_checkout_form_checkout') {
//If the user does not save the address , according to the National smart_ip to detect
if (module_exists('smart_ip')) {
if (isset($form['customer_profile_shipping'])) {
if (!isset($form['customer_profile_shipping']['addressbook'])) {
$location_data = smart_ip_get_current_visitor_location_data();
if (isset($location_data['country_code'])) {
// Add county or whatever else is needed to show other counties and states
$form['customer_profile_shipping']['commerce_customer_address']['und'][0]['#address']['country'] = $location_data['country_code'];

// Block of code below will refresh the whole form and add the proper Country and the counties etc
//create a new default addressfield to use, which will use the default values country as the default country, as opposed to the servers default
module_load_include('inc', 'addressfield', 'plugins/format/address');
$address_info = array();
$address_info['country'] = $location_data['country_code'];
$default = addressfield_default_values(array($address_info['country']=>$address_info['country']));

//where all of the data will be stored when function is called
$format = array();

//required by addressfield_format_address_generate, and returns the content as rendered
$context = array('mode' => 'render');
addressfield_format_address_generate($format, $default, $context);
//$form['customer_profile_shipping']['commerce_customer_address']['und'][0]['#address']['administrative_area'];

//new defaults and administrative_area have been generated. set these values to the already built form
$form['customer_profile_shipping']['commerce_customer_address']['und'][0]['locality_block'] = $format['locality_block'];

}
}
}
}
}
}