in cgridview there are a blank field to filter the data above every column how can I filter data depend on multi comparison creteria for example I can put >5 in this field in ID column to filter the data to be only records from id 6 and above. I want to put something like >5 and <10 how can I do that

有帮助吗?

解决方案

You create $filter instance of YourModel and implement custom search() method like its shown here:

Controller:

public function actionIndex() {
    $filter = new YourModel('search');
    $filter->unsetAttributes();
    if (isset($_GET['YourModel']))
        $filter->attributes = $_GET['YourModel'];
    $this->render('yourview', array(
        'filter' => $filter,
    ));
}

View:

<?php $this->widget('zii.widgets.grid.CGridView', array(
    'dataProvider' => $filter->search(),
    'filter' => $filter
    ...
));

As the result, attributes of $filter model contain values that user put in filter input fields of CGridView and its search() method can parse and use these values in any way to create required CDbCriteria and then return filtered CActiveDataProvider.

I didn't test it but to filter some attribute field of your model one could write something like this:

public function search()
{
    $criteria = new CDbCriteria();
    $matches = array();
    if (preg_match('/^(<|>)(.+)$/', $this->field, $matches))
    {
        $criteria->addCondition('field ' . $matches[1] . ' :field');
        $criteria->params[':field'] = $matches[2];
    }
    else
    {
        $criteria->addCondition('field = :field');
        $criteria->params[':field'] = $this->field;
    }

    // TODO: add conditions for other fields

    return new CActiveDataProvider($this, array(
        'criteria' => $criteria,
    ));
}

If you want to have both < and > conditions in one filter field it's up to you to decide which format to use and how to parse it to prepare search criteria.

其他提示

In my case i use this code:

    $matches=array();
    if(preg_match('/(.+)(\s)(.+)/',$this->field,$matches)) {
        $criteria->addCondition("field ".$matches[1]." and field ".$matches[3]);
    } else {
        $criteria->compare('field',$this->field);
    }

And in filter input in cgridview i can use "<100 >50" (whitespace character is important in this case)

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top