我是yii的新手。我想从我的模型中按属性(字段名)进行搜索,并且需要通过zii.widgets.grid.CGridView.在视图页面或另一个页面中查看
- 如何通过findByAttribute()在模型中创建search()函数
- 这样我们就可以在不进行任何搜索的情况下按属性显示结果
这是我的模型函数,但它不起作用..::错误未定义的变量:pp_requisitiono
public function searchView()
{
$criteria=new CDbCriteria();
$criteria->select= 'pp_requisitionno';
$criteria->addSearchCondition('pp_requisitionno',$pp_requisitionno);
$criteria->compare('pp_requisitionno',$this->pp_requisitionno);
$criteria->condition = 'pp_requisitionno=:pp_requisitionno';
$criteria->params = array(':pp_requisitionno'=>Yii::app()->Request->Getpost('pp_requisitionno'));
$model = Requisitiondt::model()->find();
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
请帮忙。。。
定义一个可用于不同搜索的通用搜索函数可能会更有用。这可以通过以下方式实现:
/**
* Retrieves a list of models based on the current search/filter conditions.
* @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
*/
public function search() {
$criteria = new CDbCriteria;
//Define all your searchable fields here
$criteria->compare('t.title', $this->title, true);
$criteria->compare('t.type', $this->type, true);
$criteria->compare('t.published', $this->published, true);
$criteria->compare('category.id', $this->category_id, true);
//Add any other criteria, like the default sort order etc.
return new CActiveDataProvider($this, array(
'criteria' => $criteria,
));
}
然后在你的控制器中,你可以像这样使用搜索;
pubic function actionSearch(){
$model = new Requisitiondt;
if (isset($_POST)){
$model->attributes = $_POST;
$dataProvider = $model->search();
$this->render('searchView', array('dataProvider' => $dataProvider));
}
}
视图"searchView"看起来是这样的;
<?php
$this->widget('CGridView', array(
'dataProvider' => $dataProvider,
'columns' => array(
//Add in whatever columns you want the grid to show
)
));
?>
显然,您需要替换自己的模型名称和字段名称,但这只是一般的想法。这种方式将搜索POST请求中包含的任何属性,并且更易于重用。
您需要在模型中使用Relations,请阅读此处。
然后在GridView Widget选项数组中添加'filter' => $model,