


The yii2 component implements the drop-down box with search function
This article mainly introduces the sample code of the yii2 component drop-down box with search function (yii-select2), which has certain reference value. Those who are interested can learn about
simple small functions, but It's 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. See my tutorial sharing. Composer is simply a must-have and magical. Having said that, let’s quickly use composer to install it.
No rush, let’s take a look at the renderings first, otherwise we won’t be in the mood or have the desire to read on.
What the hell are you not interested in? Just keep reading. Only then can you feel the benefits after reading it.
Youmuyou feel very handsome. Of course, it is much more than that. It is also very high-grade and the effect is amazing when used.
Okay, okay, hurry up and install it, otherwise the chat will be endless.
composer require kartik-v/yii2-widget-select2 "@dev"
Special note, because the dev version installed here is the development version and the unstable version. If your project is hosted on git, composer is installed. After that, remember to delete the .git file in the \vendor\kartik-v\yii2-widget-select2 directory, otherwise you won’t be able to submit it.
Wait for about 5 minutes and it will be installed. Then we can start using it as follows
//如果你的表单是ActiveForm,请使用 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' => '请选择 ...'], ]);
//如果你的表单是非ActiveForm,可以参考下面的 use kartik\select2\Select2; echo Select2::widget([ 'name' => 'title', 'data' => $data, 'options' => ['placeholder' => '请选择...'] ]);
When updating data generated by non-ActiveFomr It needs to be selected by default, 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? Woolen cloth? It's easier to do. Taking the above example, you only need to specify $model->title = ['title1', 'title2'];
That's basically it, we will It is very simple to implement the drop-down selection and search function. However, a but came up again, but this is what we thought just now, and the fact is this. The editor said, can you make the operation more convenient? It is too troublesome to choose one at a time. Can you choose more? ah? In order to implement your ZB trick, well, it is indeed simple and can be solved with one line of code.
echo $form->field($model, 'title')->widget(Select2::classname(), [ 'data' => $data, 'options' => ['multiple' => true, 'placeholder' => '请选择 ...'], ]); #多选的添加默认值同上
The sharp-eyed noticed that a multiple option was added. Forms generated by non-ActiveForm operate the same.
Let’s see what the effect is.
At this point, we can sing NB’s songs and go home happily
Wait, I seem to have forgotten something, any sharp-eyed friends You may have noticed that $data is all data we have prepared in advance. You said that if the amount of data is large, it will kill people. Then let us see how to implement asynchronous search results. For example, we now want to query a certain book title, but the data volume of our book is about 1 million. It is very simple. This requires us to asynchronously obtain the data in the drop-down box based on your search results. To be continued, further explanation will be given later.
Come on guys, let’s take a look at how to use the asynchronous search function. It’s very useful at work, especially when correlating data. It’s convenient. Just take a look and you’ll know. It’s easy to use. Incredible.
I won’t go into details about the basic usage. Please read the above, and we will continue to talk here.
Let’s first preview the rendering of asynchronous search
Note that the marked parts in the picture are searched by the keywords we entered. As for the effect of asynchronous, I guess you can't see the effect when I take a screenshot. I don't know how to do animations. I don't know how to do it. Can you tell me what the specific effect is? I believe most people understand it. This is called only possible. I understand but cannot express myself in words. Okay, let's just go straight to the code and see the specific operation.
// view层 use kartik\select2\Select2; use yii\web\JsExpression; <?php echo $form->field($model, 'title')->widget(Select2::classname(), [ 'options' => ['placeholder' => '请输入标题名称 ...'], '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; }'), ], ]); ?>
The above code can be copied and used directly, the only thing that needs to be modified is the corresponding url address in ajax. Let's take a look at how the controller layer code provides data.
//controller层 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; }
The above is the entire content of this article. I hope it will be helpful to everyone’s study. For more related content, please pay attention to the PHP Chinese website!
Related recommendations:
About the code for using modal pop-up windows in combination with gridview in yii2
About Yii2.0 multiple files Uploaded code
#About Yii model query based on arrays and objects
The above is the detailed content of The yii2 component implements the drop-down box with search function. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

How to remove jquery from yii2: 1. Edit the AppAsset.php file and comment out the "yii\web\YiiAsset" value in the variable $depends; 2. Edit the main.php file and add the configuration "'yii" under the field "components" \web\JqueryAsset' => ['js' => [],'sourcePath' => null,]," to remove the jquery script.

With the continuous development of cloud computing technology, data backup has become something that every enterprise must do. In this context, it is particularly important to develop a highly available cloud backup system. The PHP framework Yii is a powerful framework that can help developers quickly build high-performance web applications. The following will introduce how to use the Yii framework to develop a highly available cloud backup system. Designing the database model In the Yii framework, the database model is a very important part. Because the data backup system requires a lot of tables and relationships

How to implement a multi-select drop-down box in Vue. In Vue development, the drop-down box is one of the common form components. Normally, we use radio drop-down boxes to select an option. However, sometimes we need to implement a multi-select drop-down box so that users can select multiple options at the same time. In this article, we will introduce how to implement a multi-select drop-down box in Vue and provide specific code examples. 1. Use the ElementUI component library. ElementUI is a desktop component library based on Vue, which provides a rich UI.

As the demand for web applications continues to grow, developers have more and more choices in choosing development frameworks. Symfony and Yii2 are two popular PHP frameworks. They both have powerful functions and performance, but when faced with the need to develop large-scale web applications, which framework is more suitable? Next we will conduct a comparative analysis of Symphony and Yii2 to help you make a better choice. Basic Overview Symphony is an open source web application framework written in PHP and is built on

As the Internet continues to develop, the demand for web application development is also getting higher and higher. For developers, developing applications requires a stable, efficient, and powerful framework, which can improve development efficiency. Yii is a leading high-performance PHP framework that provides rich features and good performance. Yii3 is the next generation version of the Yii framework, which further optimizes performance and code quality based on Yii2. In this article, we will introduce how to use Yii3 framework to develop PHP applications.

In the current information age, big data, artificial intelligence, cloud computing and other technologies have become the focus of major enterprises. Among these technologies, graphics card rendering technology, as a high-performance graphics processing technology, has received more and more attention. Graphics card rendering technology is widely used in game development, film and television special effects, engineering modeling and other fields. For developers, choosing a framework that suits their projects is a very important decision. Among current languages, PHP is a very dynamic language. Some excellent PHP frameworks such as Yii2, Ph

The Yii framework is an open source PHP Web application framework that provides numerous tools and components to simplify the process of Web application development, of which data query is one of the important components. In the Yii framework, we can use SQL-like syntax to access the database to query and manipulate data efficiently. The query builder of the Yii framework mainly includes the following types: ActiveRecord query, QueryBuilder query, command query and original SQL query

If you're asking "What is Yii?" check out my previous tutorial: Introduction to the Yii Framework, which reviews the benefits of Yii and outlines what's new in Yii 2.0, released in October 2014. Hmm> In this Programming with Yii2 series, I will guide readers in using the Yii2PHP framework. In today's tutorial, I will share with you how to leverage Yii's console functionality to run cron jobs. In the past, I've used wget - a web-accessible URL - in a cron job to run my background tasks. This raises security concerns and has some performance issues. While I discussed some ways to mitigate the risk in our Security for Startup series, I had hoped to transition to console-driven commands
