3

Is there a way I can have the array from craft.commerce.countriesList automatically default to the country my store is in?

4
  • What do you mean automatically default? craft.commerce.countriesList just returns an array of id => name values from the craft_commerce_countries table in the database. You can do whatever you want with it.
    – Brad Bell
    Mar 23, 2016 at 17:25
  • 1
    well, if I'm looping over them in a select list, I'd want the UK (and perhaps the US) to be at the top of that list, rather than Afghanistan. Mar 23, 2016 at 17:57
  • I'm playing fake Luke Holder here, but I don't believe Commerce has a specific setting to specify what country your store is in. Maybe you want to match it by currency (messy) or by the locale Craft is currently using (slightly less messy).
    – Brad Bell
    Mar 23, 2016 at 18:16
  • You're entirely correct, I was confusing matters with default currency. I guess I'm looking for a way with Twig to have UK appear first in the loop. Mar 23, 2016 at 18:22

2 Answers 2

3

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>
3

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>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.