5

I my be in a bit of a "wood for the trees" situation but how is it possible to return elements based on a custom field being between two supplied values.

For example returning users based on a number field. Let's say the number field is between 1 - 100 and I want to return users that have between 5 and 10 selected.

I could do it like the following

$users = craft()->elements->getCriteria(ElementType::User, array("customNumberField"=>array(5,6,7,8,9,10))->find();

However that sets OR

I know that you can use parameters eg "customNumberField"=>"<= 10" but obviously specifying that key twice causes it to be overwritten.

You can also specify an array with the parameters (avoiding the overwriting) like so

 $users = craft()->elements->getCriteria(ElementType::User, array("customNumberField"=>array(">= 5", "<= 10"))->find();

But again this just creates customNumberField >= 5 OR customNumberField <= 10.

Is it possible to use the array as above but tell it to use AND instead of OR?

Am I on the right track or way off?

nfourtythree
  • 850
  • 7
  • 9

1 Answers1

6

You’re close! You just need to begin the array with "and":

$criteria = craft()->elements->getCriteria(ElementType::User);
$criteria->customNumberField = array('and', '>=5', '<=10');

$users = $criteria->find();

This same thing could also be accomplished from your templates like this:

{% set users = craft.users.customNumberField('and', '>=5', '<=10') %}
Brandon Kelly
  • 34,307
  • 2
  • 71
  • 137
  • Thanks! I had even tried it at the end but for some reason didn't try it at the start! – nfourtythree Aug 07 '14 at 10:29
  • Brandon, how could/should you write your twig statement in a hash? For example I am using a hash to query the following: {% set scriptsAboutToExpire = { section: 'scripts', order: 'expirationDate asc', expirationDate: 'and', '>=' ~ now, '<=' ~ now|date_modify('+2 weeks') } %} but that obviously breaks because of the commas... – Steven Thate Oct 26 '17 at 16:44
  • 3
    @StevenThate Just wrap the values in a sub-array – expirationDate: ['and', '>='~now, '<='~now|date_modify('+2 weeks')] – Brandon Kelly Oct 26 '17 at 19:51
  • @BrandonKelly, how should your answer be expressed in Craft 3? I'm having some difficulty with it :( See: https://craftcms.stackexchange.com/questions/25825/craft-3-error-variable-now-does-not-exist – Steven Thate Apr 23 '18 at 20:05