LoginSignup
7
7

More than 5 years have passed since last update.

Yii2の削除確認ダイアログをかっこ良くする

Last updated at Posted at 2014-10-21

せっかく最初からBootstrapなんだし、削除確認などに使われてるあのOS標準ダイアログなJSの confirm() ももっとかっこ良くしたい。というわけで Bootbox であれをオーバーライドします。

フレームワークの中から探しだした yii.js にはこう書いてあります。

/**
 * Displays a confirmation dialog.
 * The default implementation simply displays a js confirmation dialog.
 * You may override this by setting `yii.confirm`.
 * @param message the confirmation message.
 * @param ok a callback to be called when the user confirms the message
 * @param cancel a callback to be called when the user cancels the confirmation
 */
confirm: function (message, ok, cancel) {
    if (confirm(message)) {
        !ok || ok();
    } else {
        !cancel || cancel();
    }
},

おや

You may override this by setting yii.confirm

すばらしいですね。やってみましょう。

composer.jsonbowerbootbox を追加。ご存知のとおり、Yii2 では Composer を使って、Packagist からだけでなく、bower や npm からでもいろいろインストールできます。

{
    "require": {
        "php": ">=5.4.0",
        ...略
        "bower-asset/bootbox": "~4.3.0"
    },
}

別のプロジェクトでも使いまわせるようにBootbox用のアセットを定義し、

<?php
namespace app\assets;

use Yii;
use yii\web\AssetBundle;

class BootboxAsset extends AssetBundle
{
    public $sourcePath = '@vendor/bower/bootbox';
    public $js = [
        'bootbox.js',
    ];
}

つねにロードしておいて欲しいのでそれを app\assets\AppAsset に追加。

namespace app\assets;

use yii\web\AssetBundle;

class AppAsset extends AssetBundle
{
    // ... 略
    public $depends = [
        'yii\web\YiiAsset',
        'yii\bootstrap\BootstrapAsset',
        'app\assets\BootboxAsset', // ここ
    ];
}

ここまでで、基本、全てのページに bootbox.js が入ります。

いよいよ標準の確認ダイアログのオーバーライドです。たとえばこういう実装でいかがでしょう。

class BootboxAsset extends AssetBundle
{
    // ... 略
    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(); }
                });
            }
        ');
    }
}

というような、JSを登録できるメソッドを作っておいて、views/layouts/main.php あたりのこのへんからこう。

<?php
// ... 略
AppAsset::register($this);
BootboxAsset::overrideSystemConfirm(); // これ (もしかしたら $this 渡したほうが...?)
?>
<!DOCTYPE html>

スクリーンショット 2014-10-21 21.24.41.png

よーし!

ようするに、単に、yii.confirm を自分の関数に置き換えてるだけです。が、Yiiのアセットマネージャーを使うと、いい感じの場所で透過的にそうなってくれるので、何も気にしなくてもよくてありがたいですね。

おや、これが可能になったときのコミット にどこかで見た名前が。

7
7
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
7