I recently ran into a db that had thousands of records in ISO 3166-1-alpha-3 format (3 letters) that needed to be converted to ISO 3166-1-alpha-2 (2 letter) codes for use with addressfield. It was a pretty simple matter to modify the country_to_code.inc plugin for this.

For convenience, here's the code (patch to follow):

/**
 * @file
 * Convert an ISO Alpha3 country code to an ISO Alpha2 country code.
 */

$plugin = array(
  'form' => 'feeds_tamper_country_alpha3_to_alpha2_code_form',
  'callback' => 'feeds_tamper_country_alpha3_to_alpha2_code_callback',
  'name' => 'Country ISO Alpha3 code to ISO Alpha2 code',
  'multi' => 'loop',
  'category' => 'Other',
  'default description' => 'Convert an ISO Alpha3 country code to an ISO Alpha2 country code',
);

function feeds_tamper_country_alpha3_to_alpha2_code_form($importer, $element_key, $settings) {
  $form = array();
  $form['help'] = array(
    '#markup' => t('Converts this field from an ISO 3166-1-alpha-3 country code to the two character ISO 3166-1 alpha-2 code.'),
  );
  return $form;
}

function feeds_tamper_country_alpha3_to_alpha2_code_callback($result, $item_key, $element_key, &$field, $settings, $source) {
  static $codes = array();

  if (empty($codes)) {
    $codes =  array_flip(json_decode(file_get_contents('http://country.io/iso3.json'), true));
  }

  // If it's already a valid ISO Alpha2 country code, leave it alone.
  if (in_array($field, $codes)) {
    return;
  }

  // Find matching 2 letter code.
  $alpha3_code = drupal_strtoupper(trim($field));
  if (isset($codes[$alpha3_code])) {
    $field = $codes[$alpha3_code];
    }
  else {
    // If country cannot be found, return nothing.
    $field = '';
  }
}

Just drop that into a file named country_alpha3_to_alpha2.inc in the feeds_tamper/plugin directory, clear the caches, you should be good to go. Or, if you don't want to maintain a patch while this is being considered, just create a custom module for the plugin: https://www.drupal.org/node/1246602.

Support from Acquia helps fund testing for Drupal Acquia logo

Comments

WorldFallz created an issue. See original summary.

WorldFallz’s picture

WorldFallz’s picture

Issue summary: View changes
WorldFallz’s picture

Issue summary: View changes