Use of select2 under yii2

Time:2020-4-6

Novice, not good at writing JS, just share the problems you encounter for your reference


The plug-in select2 is a drop-down selection box with search function
The effect is as follows:
Use of select2 under yii2

Before using, make sure that your project has select2 installed. If not, use composer to install it

  • When using, first reference the plug-in in the header
use kartik\select2\Select2;
  • If the form is activeform, you can use the following code
  • $data is a key value pair array. Key value. All $data declared below are key value pair arrays. Take this array as an example
$data = [2 => 'widget', 3 => 'dropDownList', 4 => 'yii2']; 
$form->field($model, 'title')->widget(Select2::classname(), [  
    'data' => $data, 
    'options' = > please select...'], 
]);
  • If your form is not activeform, please refer to the following
Select2::widget([ 'name' => 'title', 
    'data' => $data, 
    'options' = > [' placeholder '= >' please select... '] 
]);
  • When updating data generated by non activefomr, it needs to be selected by default. Easy to do, just add value
Select2::widget([ 
    'name' => 'title', 
    'value' => 2, 
    'data' => $data, 
    'options' = > [' placeholder '= >' please select... '] 
]);
  • If you want to realize multiple selection, add a multiple option to options, that is
Select2::widget([ 
    'name' => 'title', 
    'value' => 2, 
    'data' => $data, 
    'options' = > [' multiple '= > true,' placeholder '= >' please select... '] 
]);
  • In the actual project, I get the data directly from the model layer and add the ID
$form->field($model, 'back_reason')->widget(Select2::classname(),
    [
        'name'  => 'search',
        'value' => isset($params['company_id'])?$params['company_id']:'',
        'data'  => \yii\helpers\ArrayHelper::map(\app\models\BackReason::find()->where(['level'=>\app\models\BackReason::LEVEL_2])->asArray()->all(),'id','reason'),
        'options' = >,
        'pluginOptions' => [
            'allowClear' => true,
            'width' => '220px',
        ],
    ])
  • Under normal circumstances, it can be used. However, if the select2 plug-in is used in the bootstrap mode box, there will be a problem that the plug-in can’t input, and the plug-in can’t get the focus all the time
    Use of select2 under yii2
  • 1. First, check whether there is tabIndex in the main Div. = “- 1”
  • 2. Rewrite enforcefocus method
<script>
    $(function() {
        $.fn.modal.Constructor.prototype.enforceFocus = function () {};
    });
</script>
  • If you want to implement asynchronous search function
  • 1. View layer, the code can be copied directly, only the corresponding URL address in Ajax needs to be modified
use kartik\select2\Select2;
use yii\web\JsExpression;
<? php
    echo $form->field($model, 'title')->widget(Select2::classname(), [
        'options' = >,
        'pluginOptions' => [
            'placeholder' => 'search ...',
            'allowClear' => true,
            'language' => [
                'errorLoading' => new JsExpression("function () { return 'Waiting...'; }"),
            ],
            'ajax' => [
                'URL' = >,
                'dataType' => 'json',
                'data' => new JsExpression('function(params) { return {q:params.term}; }')
            ],
            'escapeMarkup' => new JsExpression('function (markup) { return markup; }'),
            'templateResult' => new JsExpression('function(res) { return res.text; }'),
            'templateSelection' => new JsExpression('function (res) { return res.text; }'),
        ],
    ]);
? >
  • 2. Controller layer, responsible for providing data
public function actionSearchTitle ($q)
{
    \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
    $out = ['results' => ['id' => '', 'text' => '']];
    if (!$q) {
        return $out;
    }

    $data = Article::find()
                ->select('id, title as text')
                ->andFilterWhere(['like', 'title', $q])
                ->limit(50)
                ->asArray()
                ->all();
                
    $out['results'] = array_values($data);

    return $out;
}