0

I am having an issue outputting news stories that are filtered via a multi-select field, newsCategory is the the multi-select fied handle.

Here is my code

<div class="search-results search-results--col-three">
{% set selectedCategory = entry.newsCategory %}
{% set latestNews = craft.entries.section('news_entries')
.relatedTo({
 targetElement: selectedCategory,
 field: 'newsCategory'
  })
 .orderBy('postDate desc')
 .all() %}

{% for news_entry in latestNews %}
    {# Display the filtered news entries as needed. #}
{% endfor %}

There are no errors with the code but it doesn't output any stories, if I take out

 targetElement: selectedCategory,
 field: 'newsCategory'})

I get all my stories output without the filter, so it looks like the issue is with this part of the code. I am using craft 4.5 and I'm not sure if the change to entification has affected this syntax .Any help is appreciated

1 Answer 1

2

You haven't executed your element query.

Try swapping out:

{% set selectedCategory = entry.newsCategory %}

for:

{% set selectedCategory = entry.newsCategory.ids() %}
3
  • Ok tried that and I get this error : Neither the property "ids" nor one of the methods "ids()", "getids()"/"isids()"/"hasids()" or "__call()" exist and have public access in class "craft\fields\data\MultiOptionsFieldData".
    – bhackett
    Commented Sep 25, 2023 at 20:57
  • Sorry, I read your question too fast without paying enough attention! If you're using a multiselect (a questionable decision IMO, as they are a UI fraught with UX problems), then you can't use relatedTo, because the values are not elements. Only elements are "related to" each other. Instead you'd need to use a simple custom field query: craftcms.com/docs/4.x/… ... However, I'd recommend that you switch to using a proper category selector instead of a plain text multi-select field - it's a lot cleaner and more powerful. Commented Sep 26, 2023 at 9:03
  • Yes I think you are right; the custom field query is messy too. I'm going to switch to a category selector
    – bhackett
    Commented Sep 26, 2023 at 16:10

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.