CONTRANCE6: GENERATE AN AUTOCOMPLETE INPUT WITH JQUERY AUTOCOMPLETE

created: 23.05.2019 14:04

edited: 23.05.2019 14:12

back

/View/Layouts/index.php

php
<body data-base-url="<?= h(Router::url('/', true)) ?>">
   //...
</body>

/Config/routes.php

php
// Keyword Autocomplete
Router::connect(
    '/!keyword_autocomplete',
    ['plugin' => 'frontend_contents', 'controller' => 'frontend_contents', 'action' => 'keyword_autocomplete']
);

/Plugin/FrontendContents/Controller/FrontendContentsController.php

php
public function keyword_autocomplete()
    {
        $keywords = $this->Keyword->KeywordI18n->find(
            'all',
            [
                'conditions' => [
                    'KeywordI18n.keyword LIKE' => '%' . $this->request->query("keyword") . '%',
                    'language_id'              => $this->langId
                ],
            ]
        );

        $keywordList = [];
        foreach ($keywords as $keyword) {
            $keywordList [] = [
                'value' => Hash::get($keyword, 'Keyword.id'),
                'label' => Hash::get($keyword, 'KeywordI18n.keyword'),
            ];
        }
        $this->set('keywordList', $keywordList);
        $this->set(
            '_serialize',
            [
                'keywordList',
            ]
        );
    }

/webroot/js/main.js

javascript
//*************************
    // FAQ Keyword Suche
    //*************************
    $('.type-faq_form #keyword').autocomplete({
        source: function (req, resp) {
            $.getJSON($('body').data('base-url') + '!keyword_autocomplete.json', {keyword: req.term}, function (data) {
                resp(data.keywordList);
            });
        },
        select: function (event, ui) {
            $(event.target).val(ui.item.value);
            $('input#keyword').css('color', 'transparent');
            $('#faq_formForm').submit();
            return false;
        },
    });