Tuesday 25 March 2014

Check Yii CGridview empty

If you are working on Yii framework then sometime you need to check whether your CGridView widget (Generated by Yii) has empty data or not. Recently I've faced problem where I've to redirect user to create page if there is no data in CGridView depending on user's role and conditions. After couple of googling I've found few simple lines and modified my model code which worked for me.

In model: Put CActiveDataProvider into a variable:
<?php
    $dataProvider = new CActiveDataProvider($this, array(
        'criteria' => $criteria,
        'pagination' => array('pageSize' => 10),
        'sort' => array(
            'defaultOrder' => 'create_dttm DESC',
        )
    ));
?>
Check if dataprovider is empty or not:
<?php
  if (!isset($_REQUEST['ajax']) && $dataProvider->totalItemCount < 1) {
   Yii::app()->getController()->redirect(array('create'));
  } else {
   return $dataProvider;
  }    
?>
If the above code doesn't works then you can also return an empty data provider like this:
return new CActiveDataProvider($this, array('data' => array()));

No comments:

Post a Comment