3

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

  • 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 '16 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. – Steven Grant Mar 23 '16 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 '16 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. – Steven Grant Mar 23 '16 at 18:22
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>
|improve this answer|||||
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>
|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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