在CGridView中显示虚拟属性


Displaying Virtual Attribute In CGridView

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

我不应该只是能够使用$data->from_date在我的CGridView?

模型
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',
        ),
    ),
));

尝试以下调整。我不知道您在哪里指定了如何设置$_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注入漏洞,但让我们一次解决一个问题。