11

I'm looking at making a plugin and need to search news entries. I can use:

$criteria = craft()->elements->getCriteria(ElementType::Entry);
$criteria->section = 'news';
$find = $criteria->find();

However, I want to add a criteria where I search a specific field, for example: fieldabc = 'zyx'

What is the correct syntax for this?

Thanks!

  • I see I can use: $criteria->search = 'zyx'; which would suffice, but is there a way to target it to a field ? – Anthony Jul 16 '14 at 7:07
  • Hey Anthony, great question! Can you update the title to something a little more descriptive like "How to search for a specific field using getCriteria"? Thanks! – Jason McCallister Jul 16 '14 at 9:06
10

As per the (new) "Working with Elements" guide from the docs, it works the same as from your templates.

The actual list of available parameters depends on the element type. They are identical to the parameters available to your templates.

So this template example:

{% craft.entries.section('news').myPlaintextField('xyz').myLightswitchField(1) %}

Works from your plugin like so:

$criteria = craft()->elements->getCriteria(ElementType::Entry);
$criteria->section            = 'news';
$criteria->myPlaintextField   = 'xyz';
$criteria->myLightswitchField = 1;

Using custom field parameters is a fast and reliable solution if you are looking for EXACT matches. I would only use the search parameter if there's no other solution.

| improve this answer | |
7

You can use the a special search format.

$criteria-> search = 'fieldHandle:searchstring';

Learn more about searching

Hope that helps!

| improve this answer | |
1

Try something like this. Remember to check the status.

$criteria = craft()->elements->getCriteria(ElementType::Entry);
$criteria->slug = $slug;
$criteria->status = NULL;
| improve this answer | |

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.