简体   繁体   中英

YII model ::: CGridView Search by specific attribute using criteria

I am new in yii. I want to search by attribute (field name) from my model and need to view in view page or another page by zii.widgets.grid.CGridView.

  1. how can I create a search() function in model by findByAttribute()
  2. so that we can show the results by attribute without any search

here is my model function but it is not working.. :: ERROR Undefined variable: pp_requisitionno

    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,
    ));
}

Any help please...

It's probably going to be more useful to define a general search function that can be reused for different searches. This can be done in the following way:

/**
     * 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,
        ));
    }

Then in your controller you can use the search like this;

pubic function actionSearch(){
$model = new Requisitiondt;
if (isset($_POST)){
$model->attributes = $_POST;
$dataProvider = $model->search();
$this->render('searchView', array('dataProvider' => $dataProvider));
}
}

The view 'searchView' then looks like this;

<?php
$this->widget('CGridView', array(
'dataProvider' => $dataProvider,
'columns' => array(
//Add in whatever columns you want the grid to show
)
));
?>

Obviously you'll need to replace your own model names and field names, but this is the general idea. This way will search for any attributes you include in the POST request,and is more reusable.

You need use Relations in your model, read here .

Then add 'filter' => $model, in your GridView Widget options array

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM