YII2 related learning records, alert and other landscaping, confirm async, Session Flash and widgets use (vi), yii2confirm_php tutorial

Source: Internet
Author: User

YII2 related learning records, alert and other landscaping, confirm asynchronous, session Flash and Widget use (vi), yii2confirm


Well, the system comes with alert, confirm and other pop-up boxes are ugly, as a Yan control, this can endure?

Here I use Kartik-v/yii2-dialog, this is based on Bootstrap3-dialog this to do some common alert, confirm and dialog small parts package, of course, In essence or bootstrap3-dialog, you can use the native method, the native method of the usage point here, and Bootstrap3-dialog is based on BOOTSTRAP3 modals do the encapsulation. Well, that's the basic relationship. In search of this relevant knowledge, often see someone mention Bootbox, this is also a popular beautification plug-in, the basic principle is similar, the usage is slightly different, in the packagist search Yii2 Bootbox will find that there are also people for YII2 integration (or their own integration can be done, Later), it is also recommended.

Follow the instructions to install it, preferably in accordance with GitHub's instructions, since the latest is usually updated here first. Use @dev in composer. You can see the instructions here, if not successful, first composer Self-update, and then try, the original installation is also a variety of error, and then suddenly good. A little note is that the Confirm,dialog call must write a callback, otherwise it will be an error.

It's pretty. But like the Yii framework GridView confirm (like a delete button), when clicked or native, because its source code is the use of the Confirm command, fortunately, the YII framework provides a method that allows us to override the Confirm method. You can do the following:

1, we can first look at the Vendor/yiisoft/yii2/assets/yii.js file in the Confirm method: In the comments can be seen, you can use Yii.confirm to override this setting.

/* *    * Displays a confirmation dialog.    * The default implementation simply displays a JS confirmation dialog.    * setting ' yii.confirm '.    * @param message the confirmation message.    * @param OK a callback to being called when the user confirms the message    * @param cancel a callback to being called when th E User cancels the confirmation    */    confirmfunction (message, OK,  Cancel) {        if  (confirm (message)) {            !ok | | ok ();         Else {            !cancel | | cancel ();        }    },

2, then we rewrite, you can create a new confirm.js file in Backend/web/js, and then re-refer to this article, which is set Bootbox, and the version is a bit outdated, but the comments below are the latest method. And our setup is consistent with this principle, except that it is changed to the parameter style required by Kartik-v/yii2-dialog:

function (Message, OK, cancel) {    Krajeedialog. Confirm (Message,function(data) {        if  (data) {            !ok | | ok ();         Else {            !cancel | | cancel ();        }    });     // Confirm'll always return false on the first call     //To cancel click handler    return false ;}

3, we need to register this JS, you can add the above JS file in backend/assets/appasset.php:

class extends assetbundle{    public$basePath = ' @webroot ';      Public $baseUrl = ' @web ';      Public $css = [        ' css/site.css ',    ];      Public $js = [        ' js/confirm.js ',// is here     ];      Public $depends = [        ' Yii\web\yiiasset ',        ' Yii\bootstrap\bootstrapasset ',    ];}

This way, when you click the Delete button, you will find that you can call:

Since we are using Kartik-gridview, it's two functions show all records and export CSV and other hints, are used by the original confirm, obsessive-compulsive disorder can we endure it? Well, I endure, here only to change the idea, especially to understand the basic JS I, first put the time in other places.

Before we change, we need to make clear that the Kartik-v/yii2-dialog confirm (Bootbox same) is different from native confirm. The native confirm is synchronous, and the confirm method of Kartik-v/yii2-dialog is the asynchronous callback. This leads to native confirm that can be written directly like this:

function ABC () {    return window.confirm (' 123 ');//confirm Click Confirm to return True, cancel return false, do not click to wait for the user to click     }if(ABC ()) {    alert (' 456 ');   Click Yes to pop up the alert popup }

And if you write with Kartik-v/yii2-dialog's confirm, you'll never pop a window, because it's an asynchronous callback and won't wait for you to click.

function ABC () {    krajeedialog.confirm (' 123 ',function(result) {        if (Result) {            returntrue;        } Else {            returnfalse;}}    );} if (ABC ()) {    alert (' 456 ');   because it is an asynchronous callback, it does not pop the window regardless of the point.

Maybe someone would think (like me) to write like this? No, do not support such a writing, bootstrap3-dialog in such a way to return the window has no open.

if (Krajeedialog.confirm (' 123 ',function(result) {}) {    returntrue;} Else {    returnfalse;      }

So if you want to execute alert in Kartik-v/yii2-dialog's confirm, you can only put alert in the callback function:

function ABC () {    krajeedialog.confirm (' 123 ',function(result) {        if (Result) {            alert (' 456 ');        } Else {           //dosomething        }    });}

The above differences, plus is in the vendor modified in violation of the principle AH (take out very laborious, but also inherit what, and export CSV JS did not find similar to the method of Yii.js, can only re-write the introduction of what), but also I do not want to change the source of the reason. Hang Daddy. OK, here's how to change it:

1, {Toggledata} shows all records, its call confirm is the Gettoggledatascript method in vendor/kartik-v/yii2-grid/gridview.php, we can modify the return:

$url=url::current ([$this$tag]); // define the URL to jump first return "\$ (' #{$this->_togglebuttonid} '). On (' {$event} ', function (e) {    e.preventdefault ();/ /Block Click event    krajeedialog.confirm (' {$msg} ', function (data) {        if (data) {            Window.location.href= ' {$url} ';//click to jump        }    });    The following is the original method    //if (!window.confirm (' {$msg} ')) {E.preventdefault ();}});";

2. The export hint in {export} is vendor/kartik-v/yii2-grid/assets/js/ Kv-grid-export.js: This is a hassle, and it feels like you need to rewrite the associated notify method and Listenclick method. Who has finished writing, please tell me.

function (msg) {                 try  {        return window.confirm (msg);   this     }    catch  (err) {        returnTrue ;    }}

On top of that, the following is the session of the flash, we generally create the completion of the operation, need to give hints is completed or how. There is a flash method to implement in Yii, click here to see, in fact, in Adminlte this background framework has integrated the alert widget, we can find this widget in the backend/views/layout/content.php call , which is that we only need to add the Setflash method to the controller, then we can accept it in the view:

   Public function actioncreate ()    {        $modelnew  User ();         if ($model->load (Yii::$app$model,Save ()) {            $session = Yii::$app->session; // Session            $session->setflash (' success ', ' create success '); // Add Flash            return $this->redirect ([' Index ']);         Else {            return$this->render (' Create ', [                $model,             ]);        }    }

Caught: (Adminlte's alert style color is so deep, and the yii frame comes with a light color, but it does not match the background frame color)

Further expansion is, if it is a successful prompt, then I can hide after 5s, that can be set, in backend/views/layout/content.php add the following fade JS code

 
  This is a section of the JQ code that disappears after the display is set    $this->registerjs ("        $ ('. Alert-success '). Animate ({opacity : 1.0}, FadeOut (' slow ');    " );  

Alas? Why suddenly said Flash, obviously contextual not unified, bad comment! Mainly, since there is alert form of flash, that of course can also be used to display the way the window. Kartik-v/yii2-dialog Although there are alert, dialog function, but here and I want to not quite the same, so we directly call the native method to write, the main way is: (below the detailed encapsulation)

var dialogshow=bootstrapdialog.show ({    Type:BootstrapDialog.TYPE_SUCCESS,     title: ' Prompt message ', message    :' created successfully, auto close after 3s ',    Size:BootstrapDialog.SIZE_SMALL,    buttons:[        {            ' off ',            function(dialogitself) {                dialogitself.close ();            }        }    ]}); 

Of course we can write directly in the index.php, but there are a lot of things, it is better to encapsulate, OK, then follow the alert to write a popup widget to use it: (some introduction point here), in common/ Widgets new popup.php, directly paste code bar. Because just register JS, there is no return value or anything, so there is no use of the run () method.

1 Php 2 3 namespace Common\widgets; 4 5 classPopup extends \yii\bootstrap\widget 6 { 7 /* * 8 * Style array 9 * @var [type] Ten */ One Public $popupTypes= [ A' Default ' = ' Bootstrapdialog.type_default ', -' Info ' = ' bootstrapdialog.type_info ', -' Primary ' = ' bootstrapdialog.type_primary ', the' Success ' = ' bootstrapdialog.type_success ', -' Warning ' = ' bootstrapdialog.type_warning ', -' Danger ' = ' bootstrapdialog.type_warning ' - ]; + /* * - * Size Array + * @var [type] A */ at Public $sizeTypes= [ -' Nomal ' = ' bootstrapdialog.size_normal ', -' Small ' = ' bootstrapdialog.size_small ', -' Wide ' = ' bootstrapdialog.size_wide ', -' Large ' = ' bootstrapdialog.size_large ' - in ]; - /* * to * Title + * @var [type] - */ the Public $title ; * /* * $ * Size Panax Notoginseng * @var [type] - */ the Public $size ; + A Public function Init () the { +Parent:: init (); - // Default title $ if( $this->title = = = NULL ) { $ $this->title = ' message prompt ' ; - } - // Default Style the if( $this->size=== NULL|| ! isset( $this->sizetypes[ $this- size])) { -
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.