Skip to content

Instantly share code, notes, and snippets.

@piotrpog piotrpog/element-api.php
Last active Jul 25, 2019

Embed
What would you like to do?
Search sutocomplete component for Craft CMS. More info on http://craftsnippets.com/articles/search-autocomplete-component-for-craft-cms
<?php
use craft\elements\Entry;
return [
'endpoints' => [
'search.json' => function() {
// settings
$section_handle = 'articles';
$phrase = Craft::$app->request->getParam('query');
$criteria = [
'section' => $section_handle,
'search' => 'title:'.$phrase,
];
return [
'elementType' => Entry::class,
'criteria' => $criteria,
'paginate' => false,
'transformer' => function(craft\elements\Entry $entry) {
return [
'title' => $entry->title,
'url' => $entry->url,
];
},
];
},
]
];
.autocomplete-suggestions {
box-sizing: border-box;
border: 1px solid #999;
background: #FFF;
cursor: default;
overflow: auto;
}
.autocomplete-suggestion {
padding: 0.1rem 0.3rem;
white-space: nowrap;
overflow: hidden;
}
.autocomplete-no-suggestion {
padding: 0.1rem 0.3rem;
}
.autocomplete-selected {
background: #F0F0F0;
}
.autocomplete-suggestions strong {
font-weight: bold;
color: #000;
}
.autocomplete-group {
padding: 0.1rem 0.3rem;
font-weight: bold;
font-size: 1rem;
color: #000;
display: block;
border-bottom: 1px solid #000;
}
{# requires jQuery autocomplete #}
{# https://github.com/devbridge/jQuery-Autocomplete #}
<form action="">
<div class="js-search-wrapper">
<input type="text" class="js-search-input" name="search">
</div>
</form>
{% js %}
$('.js-search-input').autocomplete({
serviceUrl: '{{url('search.json')}}',
appendTo: $('.js-search-wrapper'),
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 };
})
};
}
});
{% endjs %}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.