PHP code example of keygenqt / yii2-autocomplete-ajax

1. Go to this page and download the library: Download keygenqt/yii2-autocomplete-ajax library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

keygenqt / yii2-autocomplete-ajax example snippets


<?= $form->field($model, 'complete_id')->widget(keygenqt\autocompleteAjax\AutocompleteAjax::class, [
    'url' => ['ajax/search'],
    'options' => ['placeholder' => 'Find by user email or user id.']
]) 

class AjaxController extends Controller
{
    public function actionSearch($term)
    {
        if (Yii::$app->request->isAjax) {

            sleep(2); // for test

            $results = [];
            if (is_numeric($term)) {
                /** @var User $model */
                $model = User::findOne(['id' => $term]);

                if ($model) {
                    $results[] = [
                        'id' => $model['id'],
                        'label' => $model['email'] . ' (model id: ' . $model['id'] . ')',
                    ];
                }
            } else {
                $q = addslashes($term);
                foreach (User::find()->where("(`email` like '%{$q}%')")->all() as $model) {
                    $results[] = [
                        'id' => $model['id'],
                        'label' => $model['email'] . ' (model id: ' . $model['id'] . ')',
                    ];
                }
            }
            echo Json::encode($results);
        }
    }
}