Is there a way I can have the array from craft.commerce.countriesList
automatically default to the country my store is in?
2 Answers
Not particularly proud of this code, but if you want to do it from Twig, something like this:
{% set countryList = ['United Kingdom', 'United States'] %}
{% for country in craft.commerce.countriesList() %}
{% if country != 'United Kingdom' and country != 'United States' %}
{% set countryList = countryList|merge([country]) %}
{% endif %}
{% endfor %}
<ul>
{% for country in countryList %}
<li>{{ country }}</li>
{% endfor %}
</ul>
I needed to add the country values to the array so used Brad's answer to come up with the following:
{% set countryList = [{'77':'United Kingdom'},{'233':'United States'}] %}
{% for key, country in craft.commerce.countriesList %}
{% if country != 'United Kingdom' and country != 'United States' %}
{% set key_string = key|json_encode() %}
{% set countryList = countryList|merge([{(key_string):country}]) %}
{% endif %}
{% endfor %}
The above builds the array of countries with their values. The below is the code to loop over the array and fill a select
menu with their values.
<select>
{% for country in countryList %}
{% for key, option in country %}
{% set optionValue = (model ? model.countryId : '') %}
<option value="{{ key }}" {% if key == optionValue %} selected{% endif %}>{{ option }}</option>
{% endfor %}
{% endfor %}
</select>
craft.commerce.countriesList
just returns an array ofid
=>name
values from thecraft_commerce_countries
table in the database. You can do whatever you want with it.