Is there an easy way to put certain countries at the top of the dropdown list of countries? If I were to add that feature would it be desired or should I look at doing a form alter?

Comments

mchampsee’s picture

I solved this using the following code to add United States to the top of the dropdown list. In this particular case, country field is optional so we didn't want to pre-populate United States:

function templatename_form_element(&$vars)
{
	if ($vars['element']['#field_name'] == 'field_country') {
	$optionloc = strpos ($vars['element']['#children'],'</option>');
		$vars['element']['#children'] = substr_replace ($vars['element']['#children'],'</option><option value="US">United States',$optionloc,0);
}
	return theme_form_element($vars);
}

The code looks within the generated HTML for the first instance of </option> (which in this case would be the closing tag for none option) and at that point inserts an option for United States as the first thing.

webrant’s picture

That function isn't working for me, getting "Notice: Undefined index: #field_name". Could that be because I'm using the country list in the user form (entity user)? How would the field name be called in that case?

mchampsee’s picture

I would turn on the devel module and then put in a dsm($vars); statement to see what the variable should be.

webrant’s picture

I see that the real issue is I'm trying to do this on a views exposed filter. Any suggestions for how to change the option order in list there?

mchampsee’s picture

I assume it should just be hook_form_alter

mchampsee’s picture

Just figured it out. It's of the form:

function hook_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'views_exposed_form' && $form['#id'] == '??') {
    $form['name_list']['#options'] =  array('US'=>'United States') + $form['name_list']['#options'];
  }
}

That assumes that you are using the Countries: Name - list filter. If you use something else, name_list would change to iso2_list or what have you. This would put the US before being able to choose any country. If you wanted to put any country first, that line would look something like:

$form['name_list']['#options'] = array('All' => '- Any -') +array('US'=>'United States') + $form['name_list']['#options'];

The solution I have above assumes that you want US to appear at the top as well as in its place in alphabetical order.