Country Select Examples

country_select 8.0.2
countries 5.6.0

Vanilla Form using form_with

Default Configuration


f.country_select :country_code


f.country_select :country_code, priority_countries: ["GB", "US", "LV"]


f.country_select :country_code, priority_countries: ["GB", "US", "LV"]


f.country_select :country_code, priority_countries: ["GB", "US"], prompt: "Select a Country"


f.country_select :country_code, priority_countries: ["GB", "US"], include_blank: true


f.country_select :country_code, { priority_countries: ["GB", "US"] }, class: 'required-field', required: true

With I18n Support (I18n.locale = :es)


f.country_select :country_code


f.country_select :country_code, priority_countries: ["GB", "US"]

With Only Chosen Countries


f.country_select :country_code, only: ["SG","LV"]


f.country_select :country_code, only: ["SG","LV"], sort_provided: false


f.country_select :country_code, only: ["US"], priority_countries: ["GB", "US"]

Excluding Countries


f.country_select :country_code, except: ["LV","SG"]


f.country_select :country_code, except: ["US"], priority_countries: ["GB", "US"]

Without Form Object


country_select("address", "country", only: ["GB", "FR", "DE"])


country_select(nil, "country", only: ["GB", "FR", "DE"])

Using a custom formatter

Custom formatters can be defined in an initializer to fully customize option tags.

CountrySelect::FORMATS[:with_alpha2] = lambda do |country|
  "#{country.iso_short_name} (#{country.alpha2})"
end


f.country_select :country_code, format: :with_alpha2


CountrySelect::FORMATS[:with_data_attrs] = lambda do |country|
  [
    country.iso_short_name,
    country.alpha2,
    {
      'data-country-code' => country.country_code,
      'data-alpha3' => country.alpha3
    }
  ]
end


f.country_select :country_code, format: :with_data_attrs

Formtastic

Default Configuration
  1. f.input :country_code, as: :country
  2. f.input :country_code, as: :country, priority_countries: ["GB", "US"]
With I18n Support (I18n.locale = :es)
  1. f.input :country_code, as: :country
  2. f.input :country_code, as: :country, priority_countries: ["GB", "US"]
With Only Chosen Countries
  1. f.input :country_code, as: :country, only: ["LV","SG"]
  2. f.input :country_code, as: :country, priority_countries: ["GB", "US"], only: ["US"]

Simple Form

Default Configuration
f.input :country_code
f.input :country_code, priority: ["GB", "US"]
With I18n Support (I18n.locale = :es)
f.input :country_code
f.input :country_code, priority: ["GB", "US"]
With Only Chosen Countries
f.input :country_code, only: ["LV","SG"]
f.input :country_code, priority: ["GB", "US"], only: ["US"]
With Unofficial Country Names
f.input :country_code, priority: ["United Kingdom", "US"]