【问题标题】:Redirect to create page if CGridview is empty Yii如果 CGridview 为空,则重定向以创建页面 Yii
【发布时间】:2014-03-08 10:39:12
【问题描述】:

如果 Yii CGridview 在管理页面中没有数据,我想重定向到创建页面 o/w 重定向显示带有内容的 CGridview。

例子:

Yii CGridview 为空记录显示 "emptyText"=>"No data found" 然后我想编写简单的脚本来重定向回创建页面。

我怎样才能做到这一点?

【问题讨论】:

  • 您希望在控制器操作时重定向它吗?我的意思是当您将 dataProvider 传递给您的视图时,您想要重定向或情况不同?

标签: php yii


【解决方案1】:

假设你在 actionAdmin 并且你正在使用 CActiveDataProvider 那么你可以这样写

$dataProvider=new CActiveDataProvider('Post', array(
    'criteria'=>array(
        'condition'=>'status=1',
        'order'=>'create_time DESC',
        'with'=>array('author'),
    ),
    ),
));

if($dataProvider->totalItemCount < 1)
{
$this->redirect(where ever you want);
}

如果你使用 findAll 那么你可以写

$models=YourModel::model()->findAll();
if(count($models)<1)
{
$this->redirect(where ever you want);
}

【讨论】:

  • 太棒了.. $dataProviders-&gt;totalItemCount 为我工作。谢谢
【解决方案2】:

你只需要两行。把它放在你的控制器动作中,就在$this-&gt;render(...)之前:

if(intval(YourModelName::model()->count()) == 0)
    $this->redirect('create');

【讨论】:

  • 您好,谢谢您的回答...但我已经使用了这个,但并没有完全解决我的问题。我的网格针对不同的模型在不同的条件下生成,所以我需要检查条件是否只有 gridview 为空。
【解决方案3】:

您应该在控制器中执行此操作。在你看来,你有

$this->widget('CGridView',array(
    'dataProvider'=>$model->search(),

在控制器中进行搜索,查看CActiveDataProvider是否没有返回记录,如果没有返回则重定向。我相信你可以使用 CActiveDataProvider 的 getItemCount 方法,更多请看这里http://www.yiiframework.com/doc/api/1.1/CDataProvider#getItemCount-detail

【讨论】:

  • 在管理员操作中我添加了这个条件` if (!$model->findAll()) { $this->redirect(array('create')); }` 但这种情况并不能完全解决我的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-04-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-12
  • 1970-01-01
相关资源
最近更新 更多