I'm trying to output users groups for every entries in a for loop, but it returns an empty array:

{%for entry in craft.entries.section('news') %}
    {{ dump(entry.getAuthor().getGroups()) }}
{% endfor %}

But it's working correctly in the entry page itself.

Any idea how I can return the groups in a for loop?


I spot a couple of Twig errors in your code.

First, in your for loop you're casting the entries returned by craft.entries to a variable news, but you're calling entry.getAuthor() inside the loop. Either change news to entry or entry to news.

Second, I'm not sure if craft.entries('news') actually returns anything (or at least not what you actually want) – it should probably be craft.entries.section('news').

Putting it together, this should work:

{% for entry in craft.entries.section('news') %}
    {{ dump(entry.getAuthor().getGroups()) }}
{% endfor %}

Also, since you're not reporting any error messages output by Craft, I'm guessing you haven't enabled devMode in your development environment. It's a really good idea to have devMode set to true while you're working on your code, because then Craft will report any syntax errors (like your undeclared entry variable) which will make it way easier for you to debug.

Just remember to never have devMode enabled for production environments – it's both a performance and security issue if you do.

| improve this answer | |
  • Sorry I mistyped the example (the code is a bit more complex than that). So yes craft.entries.section('news') is the correct code I use for that loop, that why I don't have any error... – pvledoux Feb 4 '16 at 14:41
  • Ok, make sure you have {% for entry... and not {% for news... as well, and your code should be legit. In which case, there are only two reasons I can think of that could cause entry.getAuthor().getGroups() to not return anything: 1. Singles doesn't have authors, so if the news section is a Single, that'd be the issue. 2. Obviously, getGroups() will return an empty array for users who aren't actually in any groups. Are you absolute sure your entry author(s) are assigned to 1 or more groups? – Mats Mikkel Rummelhoff Feb 4 '16 at 15:04
  • Sorry, I just realized that the news vs. entry issue isn't a typo at all like I thought, but that the entry variable is really unrelated to the loop and declared outside it. Is entry a Single? If not, can you confirm that its author is a member of one or more user groups? – Mats Mikkel Rummelhoff Feb 4 '16 at 15:13
  • Ops sorry I have edited it too fast. Actuality, I think I have found the issue. The list is paginated, and it looks like paginated entries are not returning the entire Entry Model for some reason. – pvledoux Feb 4 '16 at 15:15

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.