Craft CMS Stack Exchange is a question and answer site for administrators, end users, developers and designers for Craft CMS. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

If I've got an array of entries, is there a less long winded approach to convert that to an array of ids so I can use it in another lookup.

{# Look up authors that match the entered query.
{% set authorEntries = craft.users.search('fullName:*' ~ query ~ '*')|default([]) %}

{% set authorIds = [] %}
{% for author in authorEntries %}
    {% set authorIds = authorIds|merge([author.id]) %}
{% endfor %}

Thanks!

share|improve this question
up vote 3 down vote accepted

Simply append .ids() to your initial query...

{% set authorIds = craft.users.search('fullName:*' ~ query ~ '*').ids() %}

Without the .ids() method, you're actually working with an Element Criteria Model.

The behavior that you're seeing is the default... it's as if you had appended .find() to your initial query.

[.find()] will be called automatically as soon as the ElementCriteriaModel is treated like an array (that is, as soon as you... start looping through the elements)

So instead of allowing the default behavior to kick in, just apply .ids() to the initial query, and get a batch of entry IDs instead of a full array of entries

share|improve this answer
    
Thanks Lindsey. That's why I couldn't find it in the docs, I was looking in the wrong place! craftcms.com/docs/templating/… – JamesNZ yesterday

Lindsey's answer should be the accepted one, but just for kicks – here's an additional approach that makes sense if you need an array of IDs and you want to loop over the entries, as well. Calling .ids() on the ElementCriteriaModel will result in an additional database query, but using the |group and |keys filters won't:

{% set authorEntries = craft.users.search('fullName:*' ~ query ~ '*').find() %}
{% set authorIds = authorEntries|group('id')|keys %}

{% for authorId in authorIds %}
    ...
{% endfor %}

{% for author in authorEntries %}
   ...
{% endfor %}
share|improve this answer
    
Oh that's cool. Thanks Mats. Craft is tied so nicely in with Twig! – JamesNZ yesterday

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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