PHP code example of khotim / yii2-select2

1. Go to this page and download the library: Download khotim/yii2-select2 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/ */

    

khotim / yii2-select2 example snippets


echo \khotim\select2\Select2::widget([
    'name' => 'option_list',
    'data' => [
        0 => 'enhancement',
        1 => 'bug',
        2 => 'duplicate',
        3 => 'invalid',
        4 => 'wontfix'
    ],
]);

<?= $form->field($model, 'option_list')->widget(\khotim\select2\Select2::className(), [
    'data' => [
        0 => 'enhancement',
        1 => 'bug',
        2 => 'duplicate',
        3 => 'invalid',
        4 => 'wontfix'
    ],
]) 

<?= $form->field($model, 'option_list')->widget(\khotim\select2\Select2::className(), [
    'clientOptions' => [
        'escapeMarkup' => new \yii\web\JsExpression('function (markup) { return markup; }'),
        'minimumInputLength' => 1,
        'placeholder' => 'search option list...',
        'allowClear' => true,
        'ajax' => [
            'url' => \yii\helpers\Url::to(['lookup/search-option']),
            'dataType' => 'json',
            'delay' => 250,
            'data' => new \yii\web\JsExpression('function (params) {
                return {
                    q: params.term, // search term
                    page: params.page
                };
            }'),
            'processResults' => new \yii\web\JsExpression('function (data, params) {
                // parse the results into the format expected by Select2
                // since we are using custom formatting functions we do not need to
                // alter the remote JSON data, except to indicate that infinite
                // scrolling can be used
                params.page = params.page || 1;
                return {
                    results: data.items,
                    pagination: {
                        more: (params.page * 30) < data.total_count
                    }
                };
            }'),
            'cache' => true
        ]
    ]
])

public function actionSearchOption()
{
    Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
    $param = Yii::$app->request->get('q');
    $models = \app\models\OptionSearch::findAll($param);
    $data['items'] = \yii\helpers\ArrayHelper::toArray($models, [
        'app\models\OptionSearch' => [
            'id',
            'text' => function ($model) {
                return $model->name;
            }
        ]
    ]);
    
    return $data;
}

php composer.phar