4

I need help.

I want to get entries based on multiple field search. It works for basic field types like selectbox or plain text but I can't get it to work with Categories Fields.

The field size is a selectbox field and works good. The color is a Categories field and doesn't work.

The code:

$criteria = craft()->elements->getCriteria(ElementType::Entry);
$criteria->section = "houses";
$criteria->size = "big"; 
$criteria->color = "white"; // <== HOW???
$entries = craft()->elements->buildElementsQuery($criteria)->queryAll();

How do I get entries with a specific Categories Field value?

Thanks for any help.

3

Here's how you'd do it making use of the relatedTo parameter

$criteria = craft()->elements->getCriteria(ElementType::Category);
$criteria->slug = 'white';
$category = $criteria->first();

$criteria = craft()->elements->getCriteria(ElementType::Entry);
$criteria->relatedTo = array(
    'targetElement' => $category
);
$entries = $criteria->find();
  • Thanks man. We seem to have posted almost at the same time :) – Nobster Mar 30 '16 at 19:25
  • 'targetElement' = $category should be 'targetElement' => $category – Brad May 19 '17 at 21:02
4

Here's another solution which feels more correct. It uses relations and the relatedTo parameter.

// First get the all CategoryModels
$colorCriteria = craft()->elements->getCriteria(ElementType::Category);
$colorCriteria->group = 'colors';
$colorCriteria->slug = array("white");
$colorCategories = $colorCriteria->find();

// Then get the entries
$criteria = craft()->elements->getCriteria(ElementType::Entry);
$criteria->section = "houses";
$criteria->size = "big";
$criteria->relatedTo = $colorCategories;//<= Here's the fancy part. 
$entries = craft()->elements->buildElementsQuery($criteria)->queryAll();

Hopefully that helps someone else.

  • So this will find all entries that has white set at color? – Spoeken Aug 29 '16 at 14:10
1

Okey. I found a solution. Probably not the fastest because of a search but it works.

$criteria->search = "color:white";

So color is the field alias. white is the category handle to look for.

Read more about search here => https://craftcms.com/docs/searching

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.