How to programmatically populate a country field We are using the Countries module to provide country fields where editors can choose a country and it gets displayed in the frontend. Which works absolutely fine.

But we want to fill that field programmatically through a custom module. No matter what value we provide to fill the field (country name, ISO 2 code etc.) the field doesn't get populated.

We are certainly sure that there is no any error somewhere else as we are filling multiple fields in our module and all are working as expected.

We want to know in which format does the country field expect the value to be?



Clarification:

We have a field field_country in profile2 with the Country type coming through Countries module.  We are getting input in our module through following code in our form:

include_once DRUPAL_ROOT . '/includes/iso.inc';
include_once DRUPAL_ROOT . '/includes/locale.inc';

$form['country'] = array(
  '#title' =&gt; t('Country'),
  '#type' =&gt; 'select',
  '#description' =&gt; t('Please Select Your Country Where Do You Belong To.'),
  '#required' =&gt; 'true',
  '#options' =&gt; array('' =&gt; t('-Select a Country-')) + country_get_list(),
  '#default_value' =&gt; isset($values['country']) ? $values['country'] : '',
);


We have also tried '#type' =&gt; 'country' and a few other things but same result.

For submitting this value we are using the code:

$profile-&gt;field_country['LANGUAGE_NONE'][0]['value'] = $data;
I played around with this now for a little while. Seems all you need is the iso2 key to be set.

global $user;

$node = new stdClass();
$node-&gt;title = 'Lorem Ipsum';
$node-&gt;type = 'article';
node_object_prepare($node);

$node-&gt;language = LANGUAGE_NONE;
$node-&gt;uid = $user-&gt;uid;
$node-&gt;status = 1;

// In the end this was it.
$node-&gt;field_country[LANGUAGE_NONE][] = [
  'iso2' =&gt; 'FR',
];

$node = node_submit($node);
node_save($node);




Apart from that you can use the Devel module to either dump variables like that

dpm($variables);


for example in a MYMODULE_preprocess_node() hook. After you filled out a node with a country field from the UI you can use that to check which values are set. Or you can checkout node values directly by appending /devel to a node path (http://example.com/node/42/devel). Although I must admit that what I got there as output was quite misleading. All that really was needed was the iso2 key.