Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to customize default data-confirm dialog box in Yii2 Gridview

I want to change the browser's default confirm dialog (data-confirm) box which comes on click of delete button.

enter image description here

I want to replace this with custom dialog box.

Following is my Gridview Code:

<?=
    GridView::widget([
        'dataProvider' => $dataProvider,
        //'filterModel' => $searchModel,                
        'columns' => [            
            //['class' => 'yii\grid\SerialColumn'],
            'account',
            'code',  
            [
                'class' => 'yii\grid\ActionColumn',
                'header' => 'Action',
                'template' => ' {update} {delete}',
                'buttons' => [
                    'update' => function ($url, $model) {
                        return Html::a('<span class="btn-xs btn-primary">Edit</span>', $url, [
                                    'title' => Yii::t('app', 'Edit'),
                        ]);
                    },
                            'delete' => function ($url, $model) {
                        return Html::a('<span class="btn-xs btn-danger">Delete</span>', $url, [
                                    'title' => Yii::t('app', 'Delete'),
                                    //'data-confirm'=>'Are you sure you want to delete this item?',
                                    'data-method'=>'POST'
                        ]);
                    }
                        ]
                    ],
                ],
            ]);
            ?>

My JQuery code:

    confirm: function (message, title, okAction) {
        $("<div></div>").dialog({
            // Remove the closing 'X' from the dialog
            open: function (event, ui) {
                $(".ui-dialog-titlebar-close").hide();
            },
            buttons: {
                "Ok": function () {
                    $(this).dialog("ok");
                    okAction();
                },
                "Cancel": function () {
                    $(this).dialog("close");
                }
            },
            close: function (event, ui) {
                $(this).remove();
            },
            resizable: false,
            title: title,
            modal: true
        }).text(message);
    }
});

$(document).ready(function () {
    $(".delete-row").click(function () {
        $.confirm("Are you sure you want to delete this item?", "Production Control WF");
    });
});

However the confirm dialog box appearing after implementation of this code but simultaneously its redirecting as well without clicking on any button.

Any help would be appreciated.

like image 317
J.K.A. Avatar asked May 26 '15 03:05

J.K.A.


2 Answers

My answer contains two parts:

  1. Replacing the default confirm-dialog
  2. Using SweetAlert as the replacement

In the first part I explain the procedure to replace the default confirmation-dialog. This is the official and proper way to replace the Yii2-confirm-dialog globally.

In the second (optional) part I show how to use SweetAlert in Yii2 to replace the dialog.

Replacing the default confirm-dialog

Its pretty easy actually since the yii.js was overhauled since the launch of Yii2. You have to create a JS-file which you deploy to your web folder. This is done as follows:

1. Create folder for JS-File

In your web folder create a folder named js (or whatever name you wish)

2. Create the actual JS-File

In the folder from step 1 create a JS-file named for example yii_overrides.js In this file you override the yii.confirm variable with your own handler-method.

My yii_overrides.js looks like this:

/**
 * Override the default yii confirm dialog. This function is 
 * called by yii when a confirmation is requested.
 *
 * @param string message the message to display
 * @param string ok callback triggered when confirmation is true
 * @param string cancelCallback callback triggered when cancelled
 */
yii.confirm = function (message, okCallback, cancelCallback) {
   swal({
       title: message,
       type: 'warning',
       showCancelButton: true,
       closeOnConfirm: true,
       allowOutsideClick: true
   }, okCallback);
};

The swal function calls the SweetAlert-Projects beautiful alert-box. Feel free to use whatever confirmation-style or -extension you want. SweetAlert looks awesome though...

3. Add JS-File to your Yii2-asset-bundle

Open assets\AppAsset.php and add your JS-File to assure it will be added to your HTML-header. Your file should look something like this now:

class AppAsset extends AssetBundle
{
    public $basePath = '@webroot';
    public $baseUrl = '@web';

    public $css = [
        'css/site.css',
    ];
    public $js = [
        //HERE!
        'js/yii_overrides.js',
    ];
    public $depends = [
        'yii\web\YiiAsset',
        'yii\bootstrap\BootstrapAsset',

        //additional import of third party alert project
        'app\assets\SweetAlertAsset',
    ];
}

Also make sure to include the asset of your custom alert-library if necessary. You can see this on the last line of the $depends-variable in the code above.

Adding SweetAlert

If you want to use SweetAlert as well, here is how you do it. There is a yii2-extension available providing you with an asset-bundle, but it is not current and uses old filenames. It therefore doesn't work. But its VERY easy to do it yourself.

1. Add dependency to SweetAlert

In your composer.json add

"bower-asset/sweetalert": "1.1.*"

to the required section and trigger composer update. You now have the necessary files.

2. Create SweetAlertAsset

Create a file named SweetAlertAsset.php next to your AppAsset in the assets-folder of your project. This is the content:

<?php
namespace app\assets;

class SweetAlertAsset extends \yii\web\AssetBundle
{
    public $sourcePath = '@bower/sweetalert/dist';
    public $css = [
        'sweetalert.css',
    ];
    public $js = [
        'sweetalert.min.js'
    ];
}

Reference it within AppAsset as seen further above.

3. Done

Easy, wasn't it!?

like image 80
PLM57 Avatar answered Sep 29 '22 01:09

PLM57


Based on Sweet Alert 2.0 updates
i've modify the answer by PLM57

SweetAlert has changed callback functions to promises.
Here is the example override code for promise implementation:

/**
 * Override the default yii confirm dialog. This function is 
 * called by yii when a confirmation is requested.
 *
 * @param string message the message to display
 * @param string ok callback triggered when confirmation is true
 * @param string cancelCallback callback triggered when cancelled
 */
yii.confirm = function (message, okCallback, cancelCallback) {
  swal({
    title: message,
    icon: 'warning',
    buttons: true
  }).then((action) => {
    if(action){
      okCallback()
    }
  });
}

For more info on update from 1.x to 2.x, refer to this

like image 37
Kai Loon Avatar answered Sep 29 '22 00:09

Kai Loon