douzun4443 2015-05-25 19:45
浏览 218

如何在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.

展开全部

  • 写回答

4条回答 默认 最新

  • dongxietao0263 2015-05-26 00:26
    关注

    i think you only need to change $url to #

    return Html::a('<span class="btn-xs btn-danger">Delete</span>', "#", [
                   'title' => Yii::t('app', 'Delete'),
                   //'data-confirm'=>'Are you sure you want to delete this item?',
                   'data-method'=>'POST'
    ]);
    
    评论
  • dongpao2871 2015-10-30 02:49
    关注

    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!?

    展开全部

    评论
  • duanqinqiao4844 2018-04-05 22:26
    关注

    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

    评论
  • duanliusong6395 2018-08-16 06:51
    关注

    Short and simple way.

    [
        'class' => 'yii\grid\ActionColumn',
        'template' => '{view} {update} {delete}',
        'buttons' => [
            'delete' => function ($url, $model, $key) {
                return Html::a('<span class="glyphicon glyphicon-trash"></span>', $url, [
                    'data-method' => 'post',
                    'data-pjax' => 0,
                    'data-confirm' => 'Your message text'
                ]);
            },
        ]
    
    评论
编辑
预览

报告相同问题?

悬赏问题

  • ¥15 MATLAB代码补全插值
  • ¥15 Typegoose 中如何使用 arrayFilters 筛选并更新深度嵌套的子文档数组信息
  • ¥15 前后端分离的学习疑问?
  • ¥15 stata实证代码答疑
  • ¥50 husky+jaco2实现在gazebo与rviz中联合仿真
  • ¥15 dpabi预处理报错:Error using y_ExtractROISignal (line 251)
  • ¥15 在虚拟机中配置flume,无法将slave1节点的文件采集到master节点中
  • ¥15 husky+kinova jaco2 仿真
  • ¥15 zigbee终端设备入网失败
  • ¥15 金融监管系统怎么对7+4机构进行监管的
手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部