Yii2 框架 - 修改默认的确认框(confirm)样式

92 阅读1分钟

Yii 默认调用 window.confirm 来询问用户操作是否继续,样式太丑和项目 UI 不协调,下面我们使用 jQuery Comfirm 来替换默认的样式。

首先安装 jquery-confirm

npm install jquery-confirm

添加 node_modules 别名

// /config/web.php
$config = [
    'aliases' => [
        // ...
        '@node'  => '@app/node_modules'
    ],
];

新建 jquery-confirm 的资源包

// /assets/JqueryConfirmAsset.php
<?php
namespace app\assets;

use yii\web\AssetBundle;

class JqueryConfirmAsset extends AssetBundle
{
    public $sourcePath = '@node/jquery-confirm';

    public $css = [
        'dist/jquery-confirm.min.css'
    ];

    public $js = [
        'dist/jquery-confirm.min.js'
    ];
}

修改 AppAsset.php 使其依赖 JqueryConfirmAsset

// /assets/AppAsset.php
public $js = [
    'js/site.js'
];
public $depends = [
    // ...
    JqueryConfirmAsset::class,
];

修改 js/site.js 文件,重写默认的 yii.confirm 方法

// /web/js/site.js
yii.confirm = function (message, ok, cancel) {
    $.confirm({
        theme: 'bootstrap', // 可选的主题:'supervan', 'material', 'light', 'dark'
        animationSpeed: 200, // 动画速度
        title: '继续该操作?',
        content: message,
        buttons: {
            'OK': {
                text: '是',
                btnClass: 'btn-primary',
                action: function () {
                    !ok || ok()
                }
            },
            'CANCEL': {
                text: '否',
                btnClass: 'btn-default',
                action: function () {
                    !cancel || cancel()
                }
            },
        }
    })
};

调用示例

<?php
use yii\helpers\Html;

echo Html::a('删除', ['delete', 'id'=> $model->id], ['class' => 'btn btn-danger', 'data' => [
    'confirm' => '确认删除该选项?', 'method' => 'post'
]]);