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?
1 Answer
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).
-
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 GCommented Aug 4, 2016 at 18:10
-
1For 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