在CGridView中显示虚拟属性

时间:2014-06-11 03:09:52

标签: php yii

我使用了from_date& to_date属性用于搜索我的数据,并将其作为安全属性放在模型中。现在,我想在CGridview中显示与模型中的其他数据相同的from_dateto_date

我不能在我的CGridView中使用$data->from_date吗?

模型

public $from_date;
public $to_date;

public function rules() {
    array('from_date, to_date', 'safe', 'on'=>'search'),
}

public function search(){
    //....

    if(!empty($this->to_date) && !empty($this->from_date))
    {
        $criteria->addCondition("date($created_date)  >= '$this->from_date' and       date($created_date) <= '$this->to_date'");
    }
    else if(!empty($this->from_date) && empty($this->to_date))
    {
        $criteria->addCondition("date($created_date) >= '$this->from_date'");
    }
    else if(!empty($this->to_date) && empty($this->from_date))
    {
        $criteria->addCondition("date($created_date) <= '$this->to_date'");
    }

    //....
}

控制器

$model = new Tickets('search');

if (!empty($_GET)) {
    $model->ticket_id = isset($_GET['ticket_id']) ? $_GET['ticket_id'] : '';

    $model->from_date = isset($_GET['from_date']) ? $_GET['from_date'] : '';
    $model->to_date = isset($_GET['to_date']) ? $_GET['to_date'] : '';
}       


$this->render('search', array(
    'model' => $model
));

查看

$this->widget('bootstrap.widgets.TbGridView', array(
    'type' => 'striped bordered condensed',
    'dataProvider' => $model->search(),
    'columns' => array(
        array(
            'name' => 'From date',
            'type' => 'html',
            'value' => '$data->from_date',
        ),
    ),
));

1 个答案:

答案 0 :(得分:0)

尝试以下调整。我不知道您在哪里指定了$_GET属性的设置方式,因此我在CGridView中添加了标准方法。如果有效,请告诉我。

控制器:

$model = new Tickets('search');
//remove any default values
$model->unsetAttributes();

//set the attributes based on the standard syntax of how CGridview populates GET
if (!empty($_GET['Tickets'])) {
    $model->attributes = $_GET['Tickets'];
}       


$this->render('search', array(
    'model' => $model
));

模型:将ticket_id添加到规则中,以便在存在时自动处理设置。

public function rules() {
    array('from_date, to_date, ticket_id', 'safe', 'on'=>'search'),
}

查看:

$this->widget('bootstrap.widgets.TbGridView', array(
    'type' => 'striped bordered condensed',
    'dataProvider' => $model->search(),
    'filter'=>$model,//should provide default filtering
    'columns' => array(
        array(
            'name' => 'From date',
            'type' => 'html',
            'value' => '$data->from_date',
        ),
    ),
));

附注:您的模型search方法存在巨大的SQL注入漏洞,但我们要先解决一个问题。

相关问题