LIAL
LIAL

Reputation: 1634

Yii flash message doesn't show after Ajax request

Anybody know how can I show the flash message in YII framework after ajax request ? I'm using standard Gii-generated CRUD operations. When I create or update data in CGridView I see my Flash message. But when data deleted there is now flash, but Yii::app()->user->setFlash('success', 'My message') is put message in session.

my actionDelete content is

$result = $this->loadModel($id)->delete();
        if ($result)
            Yii::app()->user->setFlash('success', 'Data was deleted');
        else
            Yii::app()->user->setFlash('error', 'Error was occurred');

        if (Yii::app()->request->getIsAjaxRequest())
        {
            echo Yii::app()->user->getFlash('success');
        } else {
            $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array(index));
        }

Upvotes: 0

Views: 9579

Answers (2)

sensorario
sensorario

Reputation: 21698

You need to get flash messages. Try to put this code in your protected/layouts/main.php

<?php foreach(Yii::app()->user->getFlashes() as $key => $message) : ?>
    <div class="flash-<?php echo $key; ?>"><?php echo $message; ?></div>
<?php endforeach; ?>

Upvotes: 0

Brett Gregson
Brett Gregson

Reputation: 5923

So you are having a problem retrieving the flash message via ajax? Your controller looks fine, the getIsAjaxRequest method will be getting fired, but the problem is displaying the flash message in the DOM.

First create a div that will hold your flash message:

<div id="myflashwrapper" style=""display: none;"></div>

Then, in the script where you are calling your ajax method, you need to add in something like:

$('#myflashwrapper').html(message).fadeIn().delay(3000).fadeOut();

This simply changes the HTML content of the element with the id "myflashwrapper" to be the returned flash message. As you can see, this function is expecting a variable named "message" to be populated. We want the echo Yii::app()->user->getFlash('success'); from your delete functions getIsAjaxRequest to be returned as this value.

This means you need to modify the javascript that is exectued when you click the delete link from the default Yii CRUD views.

You do this, assuming you are using CGridView, you can use scriptMap

Yii::app()->getClientScript()->scriptMap = array(
    'jquery.yiigridview.js' => Yii::app()->baseUrl . '/js/custom.gridview.js',
    ...
);

The script file you reference here will be used instead of the default Yii script for the gridview. Obviously you only want to change one function within there, so you can get the original js file here: framework/zii/widgets/assets/gridview/jquery.yiigridview.js

Simply copy everything from that file, paste it in your custom.gridview.js file, modify the ajax function that is called on the delete and it will work

Upvotes: 3

Related Questions