0

I have managed to build the search filter structure at the twig, but I get stuck when try to convert this structure in element API,

{% if craft.request.getParam('query') %}
{% set keyword = craft.request.getParam('query') %}
{% endif %}

{% set newArray = [] %}

{% set entries = craft.entries.section('products').search('title:'~keyword).orderBy('title').all() %}
{% for ent in entries %}
    {% if ent.slug not in newArray %}
        {% set newArray = newArray|merge([ent.slug]) %}
    {% endif %}
{% endfor %}

{% set categoryEntries = craft.categories.group('prodCats').search('title:'~keyword) %}    
{% set haveCat = 0 %}
{% for categoryEntry in categoryEntries %}
    {% if categoryEntries | length %}
        {% set haveCat = 1 %}
    {% endif %}
{% endfor %} 

{% if haveCat > 0 %}
    {% set catEntries = craft.entries().section('products').relatedTo(categoryEntries) %}  
    {% for ent in catEntries %}
        {% if ent.slug not in newArray %}
            {% set newArray = newArray|merge([ent.slug]) %}
            {% set entries = entries|merge([ent]) %}
        {% endif %}
    {% endfor %}
{% endif %}

Here is my current update of element API,

$keyword = Craft::$app->request->getParam('query');      
$criteria['section'] = 'products';
$criteria['orderBy'] = 'title asc';
$criteria['search'] = 'title:'.$keyword;
$categories = Category::find()->group('prodCats')->search($keyword);
$criteria['relatedTo'] = $categories;

return [
    'elementType' => Entry::class,
    'criteria' => $criteria,
    'pretty' => true,
    'paginate' => true,                
    'resourceKey' => 'search',
    'transformer' => new SearchTransformer,
];

I fail to get the same result with the above code. The category filter didn't work as expected.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.