It is a simple small function, but it is still quite fun to use. Share it so that more people can develop faster and program happily.
If you haven’t used composer yet, you are out. Check out my tutorial sharing. Composer is simply a must-have and magical. Having said that, let’s quickly use composer to install it.
Let me show you the renderings first:
Let me tell you the specific implementation ideas:
composer require kartik-v/yii2-widget-select2 "@dev" #特别说明,因为这里安装的dev版本,也就是开发版本,不稳定版本,如果你的项目是git托管的,composer安装下来之后这里记得删掉 \vendor\kartik-v\yii2-widget-select2目录下的.git文件,不然你提交不上去的哦
Wait for about 5 minutes and it will be installed. Then we can start using it as below
//If your form is ActiveForm, please use
use kartik\select2\Select2; //$data是键值对数组哦,key-value ,下面所声明的所有$data均为键值对数组,以该数组为例 $data = [2 => 'widget', 3 => 'dropDownList', 4 => 'yii2']; echo $form->field($model, 'title')->widget(Select2::classname(), [ 'data' => $data, 'options' => ['placeholder' => '请选择 ...'], ]);
//If your form is non-ActiveForm, you can refer to the following
use kartik\select2\Select2; echo Select2::widget([ 'name' => 'title', 'data' => $data, 'options' => ['placeholder' => '请选择...'] ]);
#When updating data that is not generated by ActiveFomr, it needs to be selected by default. It is easy to handle. Just add value
use kartik\select2\Select2; echo Select2::widget([ 'name' => 'title', 'value' => 2, 'data' => $data, 'options' => ['placeholder' => '请选择...'] ]);
#But what if your form is generated by ActiveForm, but the fields are often not table fields? It’s easier to do. Taking the above example, you only need to specify $model->title = ['title1', 'title2'];
The above content is a detailed example of the drop-down box with search function in yii2 introduced by the editor. I hope it will be helpful to you. At the same time, I also thank you very much for your support of the Bangkejia website!