How to show ajax delete status in CGridView like flash messages

You are viewing revision #3 of this wiki article.
This version may not be up to date with the latest version.
You may want to view the differences to the latest version or see the changes made in this revision.

« previous (#2)next (#4) »

I've seen many tickets regarding how to show friendly delete confirmation using CGridView's CButtonColumn in ajax request. If you are using relational database, after producing CRUD functionality when you try to delete a record in ajax mode which has child record it can't be deleted and you can see the ajax loader forever. By this way you can't show the users if a record has been successfully deleted or if there are some problem in flash style (setFlash() / getFlash())

Many of you tried using the CGridView's afterAjaxUpdate property and was unable to make it work. If you look deeper:

when you click the delete button at first it performs the delete operation in the controller then it refreshes the grid using another request. 'afterAjaxUpdate' fires just after refreshing so you can't see any message just after the first delete operation.

Now I'll show you how you can achieve this functionality.

The main tricks lays under CButtonColumn properties. There is a property called afterDelete which will fire a function just after the deleting operation. We will use ajax polling request to display the deletion status. So, In the controller file just echo the message with your flash message css display style and for non ajax request set the Flash message using setFlash().

try{
    $this->loadModel($id)->delete();
    Yii::app()->user->setFlash('deleteStatus','Deleted Successfully');
    echo "<div class='flash-success'>Deleted Successfully</div>"; //for ajax
}catch(CDbException $e){
    Yii::app()->user->setFlash('deleteStatus','error message');
    echo "<div class='flash-error'>error message</div>"; //for ajax
}
                        
// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
if(!isset($_GET['ajax']))
    $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin')); 

And in your view, show the echoed message in the statusMsg place holder using data variable.

<span id='statusMsg'></span>
<?php $this->widget('zii.widgets.grid.CGridView', array(
    'id'=>'region-grid',
    'dataProvider'=>$model->search(),
    'filter'=>$model,        
    'columns'=>array(
        'name',
	array(
	    'class'=>'CButtonColumn',
            'afterDelete'=>'function(link,success,data){ if(success) $("#statusMsg").html(data); }',
	),
    ),
)); ?>

Hope this will be helpful.

17 0
30 followers
Viewed: 56 877 times
Version: Unknown (update)
Category: How-tos
Written by: hasanavi
Last updated by: adlersd
Created on: Jun 8, 2011
Last updated: 11 years ago
Update Article

Revisions

View all history

Related Articles