1

I've got a user profile field named Books. This is an Entries field that contains entries from the Books channel. The idea is that users will save books to their their profile to show they have read them.

I've also got a listing page which outputs all the books that are available.

I'd like to add a conditional that checks to see if the entry ID for a book is contained within the Books entries field in the current user's profile.

I've tried the following but it doesn't work. It outputs as true for every entry, even those that aren't saved to the user's profile. Any help would be appreciated, thanks.

{{ entry.title }}

{% if currentUser.booksField.contains("entry.id") %}
  I have read this book
{% else %}
  I haven't read this book
{% endif %}
1

I don't think contains will behave like you expect (since booksField will return an array of objects and your checking that against an integer id).

Not the prettiest, but something like this should work:

{{ entry.title }}

{% set read = false %}
{% for book in currentUser.booksField %}
    {% if book.id == entry.id %}
        {% set read = true %}
    {% endif %}
{% endfor %}

{% if read %}
    I have read this book
{% else %}
    I haven't read this book
{% endif %}

And you could make it more performant (especially if you have large numbers of books) by using https://github.com/marionnewlevant/craft-mnbreakandcontinue, which adds a {% break %} Twig tag.

0
1

My initial though was that you do not need to not put the "entry.id" in quotes because it's a variable reference, but the contains() method appear to not work as expected here even when this was corrected.

The booksField returns an ElementCriteriaModel, so you should be able to fetch the list of IDs as a plain array and then use Twig's in "containment operator" to search it:

{{ entry.title }}

{% if entry.id in currentUser.booksField.ids() %}
  I have read this book
{% else %}
  I haven't read this book
{% endif %}
2
  • Hi Isaac, thanks for this. I removed the quotes around ID but it still doesn't work I'm afraid. I'm not even sure if the 'contains' conditional is the right way of doing this, with the Entries field being an array. Any other ideas are welcome, thanks.
    – Stephen
    Jun 7 '17 at 22:28
  • 1
    @Stephen it looks like an array but it's actually a ElementCriteriaModel. I will update my answer with some additional code that I think should do what you want. Jun 8 '17 at 15:24

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.