2

I have a bit complex filtering system that I try to replicate using Element API.

So far I have this which works to a degree:

Example url: training.json?reg=124&cat=99&prod=129&erp=

'criteria' => [
            'section' => 'resources',
            'search' => (craft()->request->getParam('q') ? craft()->request->getParam('q')."*" : ''),
            'relatedTo' => [
                'and', 
                craft()->request->getParam('reg'),
                (craft()->request->getParam('cat') ? craft()->request->getParam('cat') : craft()->request->getParam('reg')),
                (craft()->request->getParam('prod') ? craft()->request->getParam('prod') : craft()->request->getParam('reg')),
                (craft()->request->getParam('erp') ? craft()->request->getParam('erp') : craft()->request->getParam('reg')),
            ],
  ...

First of all, I don't know how to deal with optional parameters, I've solved this by re-using the only required parameter - reg. It works, but it's not nice, any help here would be appreciated.

The real issue though is that I need the reg parameter to be an array with all the elements in the array having OR operator.

So basically:

Example url: training.json?reg[]=124&reg=[]=123&cat=99&prod=129&erp=

(reg[0] OR reg[1]) AND cat AND prod AND erp

Is there any way I can achieve this in element API? I've tried something in the lines of the following, but with no luck.

'relatedTo' => [
     'and', 
      ['targetRegions' => ['or', 124, 99]], 
      105, 
      231,
 ],

1 Answer 1

2

Something like this should work to combine 'and' and 'or' conditions.

'relatedTo' => [
    'and',
    ['element' => [124, 99]],
    ['element' => 105],
    ['element' => 231],
],

And this is the pattern I’m usually using to build the relatedTo param dynamically. I also try to be explicit about the direction (sourceElement / targetElement) and the relation’s field.

$query = craft()->request->getQuery();

$relatedToParam = ['and'];

if ($query['reg']) {
    $relatedToParam[] = [
        'targetElement' => $query['reg'],
        'field' => 'myRegFieldHandle',
    ];
}

// repeat for all our other relatedTo conditions

$relatedToParam = count($relatedToParam) > 1 ? $relatedToParam : null,

return [
    'criteria' => [
        'section' => 'resources',
        'relatedTo' => $relatedToParam,
    ],
];
2
  • That did the trick. I really don't know why I've used the field name instead of the 'element'. For the dynamic building of param, how would that fit into the Element API?
    – Lukigi
    Commented Jan 30, 2017 at 16:21
  • You would just use the code above in your endpoint, do the param building before returning the array with the 'criteria' and everything.
    – carlcs
    Commented Jan 30, 2017 at 16:24

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.