Yii2 使用 bootboxJS美化confirm窗口

有些关键操作比如删除,我们在执行前一般先弹出来个confirm确认窗口。

在Yii2中为一个操作添加confirm确认很容易。只需在链接出添加一个‘data-confirm' => '确实要添加?'属性。

Html::a('<i class="fa fa-plus"></i> 添加', ['create'],
    [
        'class' => 'btn btn-success btn-sm',
        'data-confirm' => '确实要添加?'
    ]);

玄机隐藏在yii.js

美中不足的是,yii使用的是原生的confirm,有点丑。如果能使用bootboxJS提供的bootstrap样式的弹窗会更好看些。

实现起来也很容易,bootbox本身就一个js文件,只需引入进来,然后覆盖yii提供的conform方法即可。

先下载最新的bootbox.min.js文件,我是放到了ackendwebjs

新建一个BootboxjsAsset.php文件

<?php
/**
 * Created by PhpStorm.
 * User: mafeifan
 * Date: 2016/06/04
 * Time: 20:23
 */

namespace backendassets;

use yii;
use yiiwebAssetBundle;

class BootboxjsAsset extends AssetBundle
{

    public $sourcePath = '@backend/web/';
    public $js = [
        'js/bootbox.min.js',
    ];
    public $depends = [
        'yiiwebYiiAsset',
        'backendassetsBootstrapAsset',
    ];

    public static function overrideSystemConfirm()
    {
        Yii::$app->view->registerJs('
            yii.confirm = function(message, ok, cancel) {
                bootbox.confirm(message, function(result) {
                    if (result) { !ok || ok(); } else { !cancel || cancel(); }
                });
            }
        ');
    }
}

注意命名空间和bootbox.min.js的位置。

因为我想在后台全局覆盖confirm弹窗。

打开backendviewslayoutsmain.php。添加如下代码。

use backendassetsAppAsset;
use backendassetsBootboxjsAsset;
AppAsset::register($this);
BootboxjsAsset::register($this);
BootboxjsAsset::overrideSystemConfirm();

大功告成,快试试效果吧。

PS : 覆盖的js代码是写在php文件中,也可写在js文件中。

参考:http://qiita.com/tanakahisateru/items/be28b7bed4566ce8fa99

原文地址:https://www.cnblogs.com/mafeifan/p/4553023.html