Yii2 使用 bootboxJS美化confirm窗口

有些关键操做好比删除,咱们在执行前通常先弹出来个confirm确认窗口。php

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

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

玄机隐藏在yii.jsbootstrap

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

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

先下载最新的bootbox.min.js文件,我是放到了\backend\web\jside

新建一个BootboxjsAsset.php文件this

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

namespace backend\assets;

use yii;
use yii\web\AssetBundle;

class BootboxjsAsset extends AssetBundle
{

    public $sourcePath = '@backend/web/';
    public $js = [
        'js/bootbox.min.js',
    ];
    public $depends = [
        'yii\web\YiiAsset',
        'backend\assets\BootstrapAsset',
    ];

    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的位置。spa

由于我想在后台全局覆盖confirm弹窗。code

打开backend\views\layouts\main.php。添加以下代码。orm

use backend\assets\AppAsset;
use backend\assets\BootboxjsAsset;
AppAsset::register($this);
BootboxjsAsset::register($this);
BootboxjsAsset::overrideSystemConfirm();

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

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

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

相关文章
相关标签/搜索