Yii 2 Dialog

Latest Stable Version Latest Unstable Version Total Downloads Monthly Downloads Daily Downloads
Thankful to Krajee!
to get more out of us.

NOTE: This extension depends on the kartik-v/yii2-krajee-base extension which in turn depends on the yiisoft/yii2-bootstrap extension. Check the composer.json for this extension's requirements and dependencies that may be updated by composer.

A widget component for Yii Framework 2.0 to easily configure and initialize popup notification dialog boxes. It provides a polyfill for the native javascript alert, confirm, and prompt dialog boxes. It includes inbuilt support for rendering rich dialog boxes via bootstrap3-dialog which makes using Bootstrap's modal more monkey-friendly. The key features provided by the library:

  • Control how you want to render JAVASCRIPT dialogs. Inbuilt quick support for following dialog types:

    • ALERT dialog

    • CONFIRM dialog

    • PROMPT dialog

    • CUSTOM dialog

  • Includes a jQuery plugin krajeeDialog (created by Krajee), that allows one to configure the bootstrap3-dialog library easily, or use the native JS alerting component, OR also configure any third party JS Notification Library to be used.

  • Advanced configuration via kartik\dialog\Dialog widget. This widget allows one to globally setup the native JS alert OR bootstrap3-dialog settings.

The preferred way to install this extension is through composer. Either run:

$ php composer.phar require kartik-v/yii2-dialog "*"

or add:

"kartik-v/yii2-dialog": "*"

to the require section of your composer.json file. Then run:

php composer.phar update

to get the updated package on your application install.

The Dialog widget (kartik\dialog\Dialog) allows you to configure plugin properties globally within a view layout OR for every view file. Note that the widget does not render any content, rather it loads the necessary assets (JS & CSS) with pre-configured settings, for developers to use it easily at runtime as a client popup dialog. The Dialog widget supports the following properties:

useNative

boolean, whether to use the native javascript dialog for rendering the popup prompts. If set to false, the bootstrap3-dialog library will be used for rendering the prompts as a modal dialog. Defaults to false.

showDraggable

boolean, whether to show a draggable cursor for draggable dialog boxes when dragging. Defaults to true.

libName

boolean, the identifying name of the public javascript variable that will hold the settings for KrajeeDialog javascript object instance. Defaults to krajeeDialog. You can override this to a different name in case you want multiple dialog library instance settings on the same page.

i18n

array, the internalization configuration for this module. Defaults to:

[
    'class' => 'yii\i18n\PhpMessageSource',
    'basePath' => '@kvdialog/messages',
    'forceTranslation' => true
]

Note:

The widget has i18n / translation features enabled. You can edit the kvdialog.php file in the messages folder for your language by submitting a new pull request.

options

array the configuration options for the bootstrap3-dialog plugin (applicable when useNative is false). You can set the plugin configuration settings here as key value pairs that can be recognized by the bootstrap3-dialog plugin.

jsPosition

array, the javascript position where KrajeeDialog global variables will be initialized. Defaults to View::POS_HEAD.

dialogDefaults

array, the configuration options to be setup as defaults for the bootstrap dialog (applicable when useNative is false). This defaults to the following configuration:

[
    Dialog::DIALOG_ALERT => [
        'type' => Dialog::TYPE_INFO,
        'title' => Yii::t('kvdialog', 'Information'),
        'buttonLabel' => Dialog::ICON_OK . ' ' . Yii::t('kvdialog', 'Ok')
    ],
    Dialog::DIALOG_CONFIRM => [
        'type' => Dialog::TYPE_WARNING,
        'title' => Yii::t('kvdialog', 'Confirmation'),
        'btnOKClass' => 'btn-warning',
        'btnOKLabel' => Dialog::ICON_OK . ' ' . Yii::t('kvdialog', 'Ok'),
        'btnCancelLabel' => Dialog::ICON_CANCEL . ' ' . Yii::t('kvdialog', 'Cancel')
    ],
    Dialog::DIALOG_PROMPT => [
        'draggable' => false,
        'title' => Yii::t('kvdialog', 'Information'),
        'buttons' => [
            [
                'label' => Yii::t('kvdialog', 'Cancel'),
                'icon' => Dialog::ICON_CANCEL
            ],
            [
                'label' => Yii::t('kvdialog', 'Ok'),
                'icon' => Dialog::ICON_OK,
                'class' => 'btn-primary'
            ],
        ]
    ],
    Dialog::DIALOG_OTHER => [
        'draggable' => true,
        'closable' => false,
        'title' => Yii::t('kvdialog', 'Information'),
        'buttons' => [
            [
                'label' => Yii::t('kvdialog', 'Cancel'),
                'icon' => Dialog::ICON_CANCEL
            ],
            [
                'label' => Yii::t('kvdialog', 'Ok'),
                'icon' => Dialog::ICON_OK,
                'class' => 'btn-primary'
            ],
        ]
    ],
]

The dialogDefaults must be setup as $key => $setting pairs, where:

$key, string, is one of the following dialog types:

  • Dialog::DIALOG_ALERT or 'alert'

  • Dialog::DIALOG_CONFIRM or 'confirm'

  • Dialog::DIALOG_PROMPT or 'prompt'

  • Dialog::DIALOG_OTHER or 'dialog'

$setting, array, consists of the following property settings for each of the above dialog types:

  • type: string, one of the bootstrap contextual color types for the bootstrap3-dialog. You can use one of these preconfigured types:

    • Dialog::TYPE_DEFAULT or 'type-default'

    • Dialog::TYPE_PRIMARY or 'type-primary'

    • Dialog::TYPE_SUCCESS or 'type-success'

    • Dialog::TYPE_DANGER or 'type-danger'

    • Dialog::TYPE_WARNING or 'type-warning'

    • Dialog::TYPE_INFO or 'type-info'

  • title: string, the title heading for the dialog box.

  • buttonLabel: string, the OK button label (applicable only for Dialog::TYPE_ALERT). Defaults to <i class="glyphicon glyphicon-ok"></i> Ok.

  • btnOKClass: string, the CSS class for the OK button (applicable only for Dialog::TYPE_CONFIRM). Defaults to btn-warning.

  • btnOKLabel: string, the OK button label (applicable only for Dialog::TYPE_CONFIRM). Defaults to <i class="glyphicon glyphicon-ok"></i> Ok.

  • btnCancelLabel: string, the Cancel button label (applicable only for Dialog::TYPE_CONFIRM). Defaults to <i class="glyphicon glyphicon-ban-circle"></i> Cancel.

  • draggable: bool, whether the dialog box is draggable (applicable only for Dialog::DIALOG_PROMPT and Dialog::DIALOG_OTHER). Defaults to false for Dialog::DIALOG_PROMPT and true for Dialog::DIALOG_OTHER.

  • closable: bool, whether the dialog box is closable (applicable only for Dialog::DIALOG_PROMPT and Dialog::DIALOG_OTHER). Defaults to true for Dialog::DIALOG_PROMPT and false for Dialog::DIALOG_OTHER.

  • buttons: array, the configuration of buttons shown in the dialog box (applicable only for Dialog::DIALOG_PROMPT and Dialog::DIALOG_OTHER). Defaults to the following configuration:

    [
        [
            'label' => Yii::t('kvdialog', 'Cancel'),
            'icon' => Dialog::ICON_CANCEL
        ],
        [
            'label' => Yii::t('kvdialog', 'Ok'),
            'icon' => Dialog::ICON_OK,
            'class' => 'btn-primary'
        ],
    ]
    

The following methods can be called via javascript within the JS library object identified by Dialog::libName. The libName defaults to krajeeDialog, so the alert method for example can be called as krajeeDialog.alert('message').

Alert

The alert method of the plugin works similar to a native Javascript alert. It takes in the following parameters:

  • message: string: The message to be displayed within the alert dialog box. Other settings for the alert dialog box can be configured via dialogDefaults property of the Dialog widget.

// JS Code
krajeeDialog.alert("Hold On! This is a Krajee alert!");

Confirm

The confirm method of the plugin works similar to a native Javascript confirm, but with a callback option. It takes in the following parameters:

  • message: string: The message to be displayed within the confirm dialog box. Other settings for the confirm dialog box can be configured via dialogDefaults property of the Dialog widget.

  • callback: function: The function to execute on confirmation (i.e. when OK button is pressed). Other settings for the confirm dialog box can be configured via dialogDefaults property of the Dialog widget.

// JS Code
krajeeDialog.confirm("Are you really sure you want to do this?", function (result) {
    if (result) { // ok button was pressed
        // execute your code for confirmation
    } else { // confirmation was cancelled
        // execute your code for cancellation
    }
});

Prompt

The prompt method of the plugin works similar to a native Javascript prompt, but with a callback option. It takes in the following parameters:

  • content: string|object: If set as a string, it is treated as a raw HTML content that will be directly displayed. Typically this is setup as a object containing of the prompt input label and placeholder properties, for example:

    {label:'Provide reason', placeholder:'Upto 30 characters...'}
    

    Other settings for the prompt dialog box can be configured via dialogDefaults property of the Dialog widget.

  • callback: function: The function to execute on confirmation (i.e. when OK button is pressed). Other settings for the prompt dialog box can be configured via dialogDefaults property of the Dialog widget.

// JS Code
krajeeDialog.prompt({label:'Provide reason', placeholder:'Upto 30 characters...'}, function (result) {
    if (result) { // ok button was pressed
        // execute your code on prompt confirmation
    } else { // prompt dialog was cancelled
        // execute your code for cancellation
    }
});

Dialog

The dialog method of the plugin can be used for generating other custom dialogs via BootstrapDialog.show. It takes in the following parameters:

  • content: string|object: If set as a string, it is treated as a raw HTML content that will be directly displayed. Typically this is setup as a object containing of the dialog input label and placeholder properties, for example:

    {label:'Provide reason', placeholder:'Upto 30 characters...'}
    

    Other settings for the dialog box can be configured via dialogDefaults property of the Dialog widget.

  • callback: function: The function to execute on confirmation (i.e. when OK button is pressed). Other settings for the dialog box can be configured via dialogDefaults property of the Dialog widget.

// JS Code
krajeeDialog.dialog('This is a custom dialog', function (result) {
    if (result) { // ok button was pressed
        // execute your code on dialog confirmation
    } else { // dialog dialog was cancelled
        // execute your code for cancellation
    }
});

Basic Usage

For a very simple usage, you can load the asset bundle in your view and render the javascript to load the bootstrap 3 modal dialog.

// view.php
use kartik\dialog\DialogAsset;
DialogAsset::register($this);
$this->registerJs("$('#your-btn-id').on('click', function(){BootstrapDialog.alert('I want banana!');});");

Advanced Usage

For advanced usage (recommended), you can render the Dialog widget in your view or view layout file as shown below. As mentioned earlier, this will not display any content directly - but will rather render all the JS and CSS needed for initializing the BootstrapDialog as per your customized settings.

use kartik\dialog\Dialog;

// Example 1: Default krajeeDialog object
echo Dialog::widget([
   'options' => [], // default options
]);

// Example 2: Custom krajeeDialogCust object
echo Dialog::widget([
   'libName' => 'krajeeDialogCust', // optional if not set will default to `krajeeDialog`
   'options' => ['draggable' => true, 'closable' => true], // custom options
]);

Then in your view, you can write your own javascript to render your alert, confirm, and prompt boxes (or a custom dialog box). For example on click of HTML buttons btn-1 and btn-2, the dialogs can be popped up as shown below:

// NOTE: This is a javascript code and must be run in Yii via 'registerJs' or via a JS File in an AssetBundle

// use krajeeDialog object instance initialized by the widget
$('#btn-1').on('click', function() {
    krajeeDialog.alert('An alert');
    // or show a confirm
    krajeeDialog.confirm('Are you sure', function(out){
        if(out) {
            alert('Yes'); // or do something on confirmation
        }
    });
});

// use krajeeDialogCust object instance as in the Widget Example 2 above
$('#btn-2').on('click', function() {
    krajeeDialogCust.alert('An alert');
    // or show a prompt
    krajeeDialogCust.prompt({label:'Provide reason', placeholder:'Upto 30 characters...'}, function(out){
        if (out) {
            alert('Yes'); // or do something based on the value of out
        }
    });
});

Examples of using the Dialog widget and the krajeeDialog plugin.

use kartik\dialog\Dialog;

// widget with default options
echo Dialog::widget();

// buttons for testing the krajee dialog boxes
$btns = <<< HTML
<button type="button" id="btn-alert" class="btn btn-info">Alert</button>
<button type="button" id="btn-confirm" class="btn btn-warning">Confirm</button>
<button type="button" id="btn-prompt" class="btn btn-primary">Prompt</button>
<button type="button" id="btn-dialog" class="btn btn-default">Dialog</button>
HTML;
echo $btns;

// javascript for triggering the dialogs
$js = <<< JS
$("#btn-alert").on("click", function() {
    krajeeDialog.alert("This is a Krajee Dialog Alert!")
});
$("#btn-confirm").on("click", function() {
    krajeeDialog.confirm("Are you sure you want to proceed?", function (result) {
        if (result) {
            alert('Great! You accepted!');
        } else {
            alert('Oops! You declined!');
        }
    });
});
$("#btn-prompt").on("click", function() {
    krajeeDialog.prompt({label:'Provide reason', placeholder:'Upto 30 characters...'}, function (result) {
        if (result) {
            alert('Great! You provided a reason: \n\n' + result);
        } else {
            alert('Oops! You declined to provide a reason!');
        }
    });
});
$("#btn-dialog").on("click", function() {
    krajeeDialog.dialog(
        'This is a <b>custom dialog</b>. The dialog box is <em>draggable</em> by default and <em>closable</em> ' +
        '(try it). Note that the Ok and Cancel buttons will do nothing here until you write the relevant JS code ' +
        'for the buttons within "options". Exit the dialog by clicking the cross icon on the top right.',
        function (result) {alert(result);}
    );
});
JS;

// register your javascript
$this->registerJs($js);
use kartik\dialog\Dialog;
use yii\web\JsExpression;

// widget with advanced custom options
echo Dialog::widget([
    'libName' => 'krajeeDialogCust', // a custom lib name
    'options' => [  // customized BootstrapDialog options
        'size' => Dialog::SIZE_LARGE, // large dialog text
        'type' => Dialog::TYPE_SUCCESS, // bootstrap contextual color
        'title' => 'My Dialog',
        'message' => 'This is an entirely customized bootstrap dialog from scratch. Click buttons below to test this:',
        'buttons' => [
            [
                'id' => 'cust-btn-1',
                'label' => 'Button 1',
                'action' => new JsExpression("function(dialog) {
                    dialog.setTitle('Title 1');
                    dialog.setMessage('This is a custom message for button number 1');
                }")
            ],
            [
                'id' => 'cust-btn-2',
                'label' => 'Button 2',
                'action' => new JsExpression("function(dialog) {
                    dialog.setTitle('Title 2');
                    dialog.setMessage('This is a custom message for button number 2');
                }")
            ],
            [
                'id' => 'cust-btn-3',
                'label' => 'Begin Loading',
                'action' => new JsExpression("function(dialog) {
                    var $button = this; // 'this' here is a jQuery object wrapping the <button> DOM element.
                    dialog.setTitle('Loading...');
                    dialog.setMessage('Content loading. Wait...');
                    $button.disable();
                    $button.spin();
                    dialog.setClosable(false);
                }")
            ],
            [
                'id' => 'cust-btn-4',
                'label' => 'End Loading',
                'action' => new JsExpression("function(dialog) {
                    var $button = dialog.getButton('cust-btn-3'); // get loading button
                    $button.enable();
                    $button.stopSpin();
                    dialog.setTitle('Information');
                    dialog.setMessage('Loading Complete.');
                    dialog.setClosable(true);
                }")
            ],
        ]
    ]
]);

// button for testing the custom krajee dialog box
echo '<button type="button" id="btn-custom" class="btn btn-success">Custom Dialog</button>';

// javascript for triggering the dialogs
$js = <<< JS
$("#btn-custom").on("click", function() {
    krajeeDialogCust.dialog(
        "Welcome to a customized Krajee Dialog! Click the close icon on the top right to exit.",
        function(result) {
            // do something
        }
    );
});
JS;

// register your javascript
$this->registerJs($js);

yii2-dialog is released under the BSD 3-Clause License. See the bundled LICENSE.md for details.