Yii 1.1: How to show ajax delete status in CGridView like flash messages

33 followers

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();
    if(!isset($_GET['ajax']))
        Yii::app()->user->setFlash('success','Normal - Deleted Successfully');
    else
        echo "<div class='flash-success'>Ajax - Deleted Successfully</div>";
}catch(CDbException $e){
    if(!isset($_GET['ajax']))
        Yii::app()->user->setFlash('error','Normal - error message');
    else
        echo "<div class='flash-error'>Ajax - 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 admin (or other where you have the {delete} in GridView) view, show the echoed message in the statusMsg place holder using data variable.

<div id="statusMsg">
<?php if(Yii::app()->user->hasFlash('success')):?>
    <div class="flash-success">
        <?php echo Yii::app()->user->getFlash('success'); ?>
    </div>
<?php endif; ?>
 
<?php if(Yii::app()->user->hasFlash('error')):?>
    <div class="flash-error">
        <?php echo Yii::app()->user->getFlash('error'); ?>
    </div>
<?php endif; ?>
</div>
<?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); }',
    ),
    ),
)); ?>

This way everything works even if you disable ajax requests in GridView using:

$this->widget('zii.widgets.grid.CGridView', array(
    'id'=>'region-grid',
    'dataProvider'=>$model->search(),
    'filter'=>$model,
    'ajaxUpdate'=>false,
    'columns'=>array(
...

Hope this will be helpful.

Total 12 comments

#15097 report it
szewciu at 2013/10/07 06:40am
CGridview filtering

Flash messages are not visible when cgridview table is filtered.

#14836 report it
lisseth23 at 2013/09/13 12:30pm
Display flash message (CListView)

In the index I have a ajaxLink and I want to show a flash message when updating a record from this ajaxLink. Is this possible?

#14272 report it
logudotcom at 2013/07/31 12:30pm
It is helpful

Thanks a lot. It is so simple and works like charm!!

#8874 report it
olivier at 2012/07/05 01:08pm
BRAVO !!!

spent a day trying many solutions on the various forums and other...

YOUR SOLUTION WORKS !

thanks a lot for this. Hope I'll progress soon enough to help others also.

Cheers Olivier

#6564 report it
BornToDrink at 2012/01/18 04:34pm
Delete status

Very useful solution, thanks! Works for me with v1.1.9.

#6030 report it
chriscao at 2011/12/06 09:38pm
Show ajax delete status in CGridView like flash messages after batch deleting

Add a CJuiButton:

<?php
$deleteUrl = $this->createUrl('region/delete');
$this->widget('zii.widgets.jui.CJuiButton', array(
        'name' => 'btnDelete',
        'caption' => 'Delete',
        'buttonType' => 'button',
        'themeUrl' => Yii::app()->baseUrl . '/css/jui',
        'theme' => 'redmond',
        'cssFile' => array('jquery-ui.css'),
        'options' => array('icons' => 'js:{primary:"ui-icon-closethick"}'),
        'onclick' =>
        'js:function()
                {
                    var th=this;
                    var afterDelete=function(link,success,data){ if(success) $("#statusMsg").html(data); };
                    var selectionIds = $.fn.yiiGridView.getSelection("region-grid");
                    if (selectionIds.length!==0) {
                        if(!confirm("Are you sure you want to delete selected items?")) return false;
                        $.fn.yiiGridView.update("region-grid", {
                        type:"POST",
                        url:"' . $deleteUrl . '",
                        data: {ids: selectionIds},
                        dataType: "text",
                        success:function(data) {
                        $.fn.yiiGridView.update("region-grid");
                        afterDelete(th,true,data);
                        },
                        error:function(XHR) {
                        return afterDelete(th,false,XHR);
                        }
                        });
                    }
                    else
                    {
                        alert("nothing selected");
                    }
                    this.blur();
                    return false;
                }',
        )
);
 
 
$this->widget('zii.widgets.grid.CGridView', array(
    'id'=>'region-grid',
    'dataProvider'=>$model->search(),
    'filter'=>$model,
    'selectableRows' => 2,
    'columns'=>array(
     .....
?>
#6013 report it
chriscao at 2011/12/05 08:50pm
How to implement it on batch deleting?

It's very helpful for me.

Would you like to show an example for batch deleting records in a gridview?

Thanks!

#4695 report it
YIINewBy at 2011/08/04 05:48pm
@Implementation

Why not upgrade to the latest version? I had the exact problem as you do, but I decided to upgrade from yii-1.1.4 to 1.1.8 and everything still worked for me. You can still keep the old framework and just switch between old and new in the index.php file. Also clear the assets before upgrading. You can loose anything.

#4278 report it
hasanavi at 2011/06/21 06:00pm
@kaliwangansyah

Those code needs to be placed in your controller.

public function actionDelete($id)
{
  if(Yii::app()->request->isPostRequest)
  {
    //place the code here
  }
}

Hope this will help you

#4236 report it
at 2011/06/17 11:35pm
this code must place in where?

this code must place in where? Sory because i am newbie can you explain for newbie...

try{
    $this->loadModel($id)->delete();
    if(!isset($_GET['ajax']))
        Yii::app()->user->setFlash('success','Normal - Deleted Successfully');
    else
        echo "<div class='flash-success'>Ajax - Deleted Successfully</div>";
}catch(CDbException $e){
    if(!isset($_GET['ajax']))
        Yii::app()->user->setFlash('error','Normal - error message');
    else
        echo "<div class='flash-error'>Ajax - 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'));
#4230 report it
Maurizio Domba Cerin at 2011/06/17 06:24am
@jpgasa21

afterDelete was added in Yii 1.1.7

#4221 report it
jogasa21 at 2011/06/16 09:43pm
Implementation

I tried to implement this solution, but it doesn't work because in Yii 1.1.6 the CButtonColumn.afterDelete property does not exist.

Leave a comment

Please to leave your comment.

Write new article