0

I'm working on the search Autocomplete based on this article, http://craftsnippets.com/articles/search-autocomplete-component-for-craft-cms

Besides the title, I want to search within the category too. How can I do that? The below code doesn't work as expected.

'/search.json' => function() {
    $criteria = [
        'section' => 'products', 
        'search' => (Craft::$app->request->getParam('query')) ? 'title:'.'*'.(Craft::$app->request->getParam('query')).'*'.' OR ' . 'categories:'.'*'.(Craft::$app->request->getParam('query')).'*' : '',
        'orderBy' => 'title asc'
    ];

    return [
        'elementType' => Entry::class,
        'criteria' => $criteria,
        'pretty' => true,
        'paginate' => false ,                
        'resourceKey' => 'search',
        'transformer' => function(craft\elements\Entry $entry) {
            return [
                'title' => $entry->title . '-' . $entry->categories,
                'url' => $entry->url,
            ];
        },
    ];
},

Here is my function,

$('#search').autocomplete({
    serviceUrl: '/search.json',
    appendTo: $('.auto-complete'),
    onSelect: function (suggestion) {
        window.location.href = suggestion.url;
    },
    transformResult: function(response){
        return {
            suggestions: $.map(JSON.parse(response).data, function(dataItem) {
                return { 
                    value: dataItem.title, 
                    url: dataItem.url 
                };
            })
        };
    }
});

My category is under 'craft.categories.group('prodCats')'

2
  • Hi, maybe you could split this up into 2 queries. At first you search products by title and secondly search categories by title and return all entries that are related to that categories.
    – Johannes
    Apr 19 '20 at 8:12
  • @Johannes You mean split it during the autocomplete function? Or during the element-api?
    – Lee
    Apr 20 '20 at 9:31

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.