Country Fields

The Country field allows authors to select from a the same list of countries made available via address elements. When viewed as part of a form in the control panel, countries’ names will be localized into the user’s preferred language.

# Settings

This field has no configurable options.

You can switch other text-based fields to use the Country field type. As long as your existing field’s values are valid two-letter country codes (or empty) and the existing field

# Development

Craft stores the field’s value as a capitalized, two-letter country code.

{% if is not empty %}
  Country code: {{ }}
{% endif %}

To get more information about the country, use the address repository available via the address service:

{# Load all country data: #}
{% set repo = %}

{# Get just the selected country: #}
{% set country = repo.get( %}

{# Use properties of the country model: #}
{{ }} ({{ country.threeLetterCode }})

The country variable in this example is an instance of CommerceGuys\Addressing\Country\Country (opens new window).

# Querying by Country

You can query for elements based on a country field’s value in a familiar way:

{% set letters = craft.entries
    .all() %}

# Front-end Forms

Update the value of a country field on an element by submitting a two-letter country code to the entries/save-entry action. Supposing we are in a template used by the “Letters” section from the previous example, our form might look something like this:

{% set countries = %}

<form method="post">
  {{ csrfInput() }}
  {{ actionInput('entries/save-entry') }}
  {{ hiddenInput('canonicalId', }}

  {{ input('text', 'title', entry.title) }}

  <select name="fields[toCountry]">
    {% for country in countries %}
      {{ tag('option', {
        value: country.countryCode,
        selected: country.countryCode == entry.toCountry,
      }) }}
    {% endfor %}

Controller Actions
Read more about using forms to submit data to Craft controllers.