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.

Nobster
  • 93
  • 4

3 Answers3

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.

Nobster
  • 93
  • 4
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();
carlcs
  • 36,220
  • 5
  • 62
  • 139
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

Nobster
  • 93
  • 4