3

I can use getLocales() off of the entry model to get all locales in the system, and whether they are enabled by default for that entry type, but it doesn't actually return which locales are enabled for that given entry. Am I missing something?

2
  • 1
    Is it in the context of a plugin/PHP or Twig?
    – Brad Bell
    Commented Aug 3, 2016 at 23:29
  • Plugin/PHP. I'm actually using ElementAPI to return all entries from a section and I want to show users what locales each entry is available in.
    – Jameal G
    Commented Aug 4, 2016 at 14:04

1 Answer 1

5

Actually, entry.getLocales() (or just entry.locales) will return an array of the locales enabled for the entry's section, not all locales in the system.

Unfortunately, there's no easy way to determine which locales a single entry is enabled for. One way to do it, is to use a craft.entries query per locale, and add the locale ids to an array whenever you get an element back from the query:

{% set localesEnabledForEntry = [entry.locale] %}
{% for locale in entry.locales|keys %}
    {% set localeEntry = locale not in localesEnabledForEntry ? craft.entries.id(entry.id).locale(locale).first() : null %}
    {% if localeEntry %}
        {% set localesEnabledForEntry = localesEnabledForEntry|merge([locale]) %}
    {% endif %}
{% endfor %}

Of course, if you're looping through a lot of entries (and/or you have a lot of locales enabled for the entries' section(s)), this will quickly become a performance issue (you're basically doing 1 additional database query per entry per locale, except for the current locale being viewed).

2
  • That makes sense. I'm actually doing this in PHP with the ElementAPI plugin but I can see how that twig would easily translate. Probably couldn't take that performance hit though... I wonder if it's feasible to get it in one query with a direct query to the database.
    – Jameal G
    Commented Aug 4, 2016 at 18:10
  • 1
    For sure - I assumed you needed to do this in a template, but the concept is easily translatable to PHP. However once you're in PHP land a custom database query would make way more sense, and also avoid the performance hit. Commented Aug 4, 2016 at 18:21

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.