我正在使用Yii 1.1.16,并尝试使用CGridView来显示搜索结果列表。我也需要它能够过滤掉这些。就像默认actionAdmin
函数的工作方式一样。
这是我的控制器中的代码:
public function actionajaxResearchList()
{
if(Yii::app()->request->isAjaxRequest)
{
$year = $_POST['year'];
$criteria = new CDbCriteria();
$criteria->addCondition("year=:year");
$criteria->params = array(':year' => $year, );
$query = Abc::model()->findAll($criteria);
if ($query===null)
throw new CHttpException(404, 'The requested page does not exist.');
$model=new Abc('search');
$model->unsetAttributes();
if(isset($_GET['Abc']))
$model->attributes=$_GET['Abc'];
$this->renderPartial('_view',array(
'model'=>$model,
'query'=>$query
));
Yii::app ()->end();
}
}
在我的_view.php
中,我有这个
<?php $this->widget('zii.widgets.grid.CGridView', array(
'id'=>'abc-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
array(
'name'=>'photo',
'value'=> '$data->photo',
'type'=>'raw',
'filter'=>false, //remove filter search for photo's
),
'id',
'year',
array(
'class'=>'CButtonColumn',
),
),
)); ?>
如何让它显示我的$query
结果?我应该尝试使用过滤器功能,还是有更简单的方法?
这是一个粗略的代码,它应该可以工作,但我还没有测试过:
控制器操作:
public function actionajaxResearchList()
{
if(Yii::app()->request->isAjaxRequest)
{
if(isset($_POST['year']) && $_POST['year'] != "") {
$year = $_POST['year']; //sanitize and validate this
} else {
$year = ""; //sanitize and validate this
}
$model=new Abc('search');
$model->unsetAttributes();
if(isset($_GET['Abc']))
$model->attributes=$_GET['Abc'];
$this->renderPartial('_view',array(
'model'=>$model,
'year'=>$year // passing the year
));
Yii::app ()->end();
}
}
_view.php:
<?php $this->widget('zii.widgets.grid.CGridView', array(
'id'=>'abc-grid',
'dataProvider'=>$model->search($year),// year from controller
'filter'=>$model,
'columns'=>array(
array(
'name'=>'photo',
'value'=> '$data->photo',
'type'=>'raw',
'filter'=>false, //remove filter search for photo's
),
'id',
'year',
array(
'class'=>'CButtonColumn',
),
),
)); ?>
型号搜索:
public function search($year)
{
$criteria=new CDbCriteria;
...
if($year != "") {
$criteria->compare('year',$year);
//$criteria->addSearchCondition('year',$year);
} else {
$criteria->compare('year',$this->year);
}
...
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}