


Detailed explanation of how to use modal pop-up window example code in combination with gridview in yii2, yii2gridview_PHP tutorial
Jul 12, 2016 am 08:49 AMDetailed explanation of how to use modal pop-up window in yii2 combined with gridview. In the previous article, yii2gridview
introduced to you how to use modal pop-up window in Yii2 (basic use), that is Take creation as an example.
In actual development, we often encounter situations where modal is used to modify the data on the list page. If it is a general loop display, I believe most people can operate it after seeing the basic use of modal. However, it is estimated that some people will be able to operate it when combined with gridview. It’s starting to get too much, let’s see how to solve this problem!
1. Add an [Update] button to the gridview operation, and specify the value of data-toggle data-target class and data-id
[ 'class' => 'yii\grid\ActionColumn', 'template' => '{update}', 'buttons' => [ 'update' => function ($url, $model, $key) { return Html::a('更新', '#', [ 'data-toggle' => 'modal', 'data-target' => '#update-modal', 'class' => 'data-update', 'data-id' => $key, ]); }, ], ],
2. Add modal for update
<?php use yii\bootstrap\Modal; // 更新操作 Modal::begin([ 'id' => 'update-modal', 'header' => '<h4 class="modal-title">更新</h4>', 'footer' => '<a href="#" class="btn btn-primary" data-dismiss="modal">Close</a>', ]); $requestUpdateUrl = Url::toRoute('update'); $updateJs = <<<JS $('.data-update').on('click', function () { $.get('{$requestUpdateUrl}', { id: $(this).closest('tr').data('key') }, function (data) { $('.modal-body').html(data); } ); });
JS;
$this->registerJs($updateJs); Modal::end(); ?>
3. Modify our update method
public function actionUpdate($id) { $model = $this->findModel($id); if ($model->load(Yii::$app->request->post()) && $model->save()) { return $this->redirect(['index']); } else { return $this->renderAjax('update', [ 'model' => $model, ]); } }
It can be seen that the whole process is no different from the basic use of modal we mentioned before. But it doesn’t end here. I believe most people may encounter the following common problems that are difficult to solve:
select2 is used in yii2 modal. Why is the search box not searchable?
yii2 There are multiple modals on a single page. Why do the pages share one page and wait until the data is loaded?
yii2 A single page has multiple modals. Take modal as an example when adding a single page and updating the gridview above. When using select2, why does the updated select2 become invalid and ineffective?
Let’s see how to solve these problems one by one:
First of all, the first question is that you only need to specify the tabindex of the options option to false when modal uses begin. The reference is as follows:
Modal::begin([ // ...... 'options' => [ 'tabindex' => false ], ]);
The second and third problems are caused by using multiple modals in a single page. To illustrate the problem, we use modals in both the [Create] button in a list and the [Update] button in the gridview. . According to how to use modal pop-ups in Yii2 (basic use) and this article, the first problem is obviously
$('.modal-body').html(data);
Caused by multiple modals, after we use the modal for the first time, values ??are assigned to the bodies of all modals, so that when other modals are used later, the same content is displayed before the data is requested. To solve this problem, you only need to assign a separate value to the respective modal-body after each asynchronous request. The code can be referenced as follows:
$('#create').on('click', function () { $.get('url', {}, function (data) { $('#create-modal').find('.modal-body').html(data); // $('.modal-body').html(data); } ); }); $('.data-update').on('click', function () { $.get('{$requestUpdateUrl}', { id: $(this).closest('tr').data('key') }, function (data) { $('#update-modal').find('.modal-body').html(data); // $('.modal-body').html(data); } ); });
Look at the last question, students who have used select2 should pay attention! ! !
If like the example introduced in this topic, if select2 is included in the form, it will cause the select2 field to be normal only during [create], and the select2 field will be "hidden" during the [update] operation!
This is actually caused by the ID corresponding to the same select2 on the same page. To solve this problem, you only need to remove all existing form items on the page before each asynchronous request for data. See the specific implementation:
$('#create').on('click', function () { // 有效避免multiply modal select2的問(wèn)題 // 移除異步加載過(guò)來(lái)的form表單 $('.document-nav-form').remove(); $.get('{$requestUrl}', {}, function (data) { $('#create-modal').find('.modal-body').html(data); } ); }); $('.data-update').on('click', function () { // 有效避免multiply modal select2的問(wèn)題 // 移除異步加載過(guò)來(lái)的form表單 $('.document-nav-form').remove(); $.get('{$requestUpdateUrl}', { id: $(this).closest('tr').data('key') }, function (data) { $('#update-modal').find('.modal-body').html(data); } ); });
The above is the entire description of the example code of how to use modal pop-up window combined with gridview in yii2 introduced by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will promptly Reply to everyone. I would also like to thank you all for your support of the Bangkejia website!

Hot AI Tools

Undress AI Tool
Undress images for free

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

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

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

TosecurelyhandleauthenticationandauthorizationinPHP,followthesesteps:1.Alwayshashpasswordswithpassword_hash()andverifyusingpassword_verify(),usepreparedstatementstopreventSQLinjection,andstoreuserdatain$_SESSIONafterlogin.2.Implementrole-basedaccessc

To safely handle file uploads in PHP, the core is to verify file types, rename files, and restrict permissions. 1. Use finfo_file() to check the real MIME type, and only specific types such as image/jpeg are allowed; 2. Use uniqid() to generate random file names and store them in non-Web root directory; 3. Limit file size through php.ini and HTML forms, and set directory permissions to 0755; 4. Use ClamAV to scan malware to enhance security. These steps effectively prevent security vulnerabilities and ensure that the file upload process is safe and reliable.

In PHP, the main difference between == and == is the strictness of type checking. ==Type conversion will be performed before comparison, for example, 5=="5" returns true, and ===Request that the value and type are the same before true will be returned, for example, 5==="5" returns false. In usage scenarios, === is more secure and should be used first, and == is only used when type conversion is required.

The methods of using basic mathematical operations in PHP are as follows: 1. Addition signs support integers and floating-point numbers, and can also be used for variables. String numbers will be automatically converted but not recommended to dependencies; 2. Subtraction signs use - signs, variables are the same, and type conversion is also applicable; 3. Multiplication signs use * signs, which are suitable for numbers and similar strings; 4. Division uses / signs, which need to avoid dividing by zero, and note that the result may be floating-point numbers; 5. Taking the modulus signs can be used to judge odd and even numbers, and when processing negative numbers, the remainder signs are consistent with the dividend. The key to using these operators correctly is to ensure that the data types are clear and the boundary situation is handled well.

Yes, PHP can interact with NoSQL databases like MongoDB and Redis through specific extensions or libraries. First, use the MongoDBPHP driver (installed through PECL or Composer) to create client instances and operate databases and collections, supporting insertion, query, aggregation and other operations; second, use the Predis library or phpredis extension to connect to Redis, perform key-value settings and acquisitions, and recommend phpredis for high-performance scenarios, while Predis is convenient for rapid deployment; both are suitable for production environments and are well-documented.

TostaycurrentwithPHPdevelopmentsandbestpractices,followkeynewssourceslikePHP.netandPHPWeekly,engagewithcommunitiesonforumsandconferences,keeptoolingupdatedandgraduallyadoptnewfeatures,andreadorcontributetoopensourceprojects.First,followreliablesource

PHPbecamepopularforwebdevelopmentduetoitseaseoflearning,seamlessintegrationwithHTML,widespreadhostingsupport,andalargeecosystemincludingframeworkslikeLaravelandCMSplatformslikeWordPress.Itexcelsinhandlingformsubmissions,managingusersessions,interacti

TosettherighttimezoneinPHP,usedate_default_timezone_set()functionatthestartofyourscriptwithavalididentifiersuchas'America/New_York'.1.Usedate_default_timezone_set()beforeanydate/timefunctions.2.Alternatively,configurethephp.inifilebysettingdate.timez
