1

What is the best way to implement a typeahead search in Craft. I looked at using ElementAPI to do something similar at this example but it doesn't seem to allow me to wildcard search

https://craftcms.com/docs/templating/search-form

Here's an example of the endpoints I have configured:

I have one entry with a title of "test" when I call the API doing

When I call /entries/te its returns 0 results. When I call /entries/test it returns 1 result.

<?php

namespace Craft;
return [
    'endpoints' => [

        'entries/<search:\w+>' => function($search) {
            return [
                'elementType' => 'Entry',
                'criteria' => ['title' => $search]
            ];
        }

    ]
];
5
  • 1
    Could you elaborate on what you mean by "wildcard search?" What have you tried, already, within your criteria block in the ElementAPI configuration? – August Miller Oct 6 '16 at 18:12
  • Essentially, I want to be able to search for entries using any syntaxes mention here craftcms.com/docs/searching. When I use the ElementAPI is only returns the results when using the exact word. – jpoiri Oct 6 '16 at 18:30
  • Can you edit the original question and share the relevant portion of your Element API config where you're trying to perform the search? – Brad Bell Oct 6 '16 at 18:37
  • Ahh, not so much element-api related, but basically this answer is what you're looking for I'm guessing? craftcms.stackexchange.com/a/5477/57 – Brad Bell Oct 6 '16 at 20:15
  • @BradBell this is exactly what I would like to do but throught the ElementAPI so can return JSON – jpoiri Oct 7 '16 at 13:32
2

If you want to enable fuzzy searching globally (across the entire Craft install - CP, front-end, ElementAPI, etc.), you can use the defaultSearchTerms config setting.

You can also just do it programmatically from the ElementAPI plugin with something like:

Suffix wildcard:

'criteria' => ['title' => $search ~ '*']

Prefix wildcard:

'criteria' => ['title' => '*' ~ $search]

Both sides:

'criteria' => ['title' => '*' ~ $search ~ '*']

Or you can use any of the other search syntaxes listed on the search docs page.

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.