Support for Drupal 7 is ending on 5 January 2025—it’s time to migrate to Drupal 10! Learn about the many benefits of Drupal 10 and find migration tools in our resource center.
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
Comment #1
mchampsee CreditAttribution: mchampsee commentedI 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:
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.Comment #2
webrant CreditAttribution: webrant commentedThat 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?
Comment #3
mchampsee CreditAttribution: mchampsee at Champsee Solutions, LLC commentedI would turn on the devel module and then put in a
dsm($vars);
statement to see what the variable should be.Comment #4
webrant CreditAttribution: webrant commentedI 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?
Comment #5
mchampsee CreditAttribution: mchampsee at Champsee Solutions, LLC commentedI assume it should just be hook_form_alter
Comment #6
mchampsee CreditAttribution: mchampsee at Champsee Solutions, LLC commentedJust figured it out. It's of the form:
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.