1

我想显示我的属性列表(id、name、price、discount)和不是属性的(total_price)列。

当我使用此代码时,它显示数据表但我无法在列中搜索或排序(total_price)

任何人都可以帮助我吗?

<?php $this->widget('zii.widgets.grid.CGridView', array(
'id'=>'product-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
    'id',
    'name',
    array(
            'header' =>'Price',
            'name'=>'price',
            'value'=>'$data->price',
    ),
    array(
            'header' =>'Discount',
            'name'=>'discount',
            'value'=>'$data->discount',
    ),
    array(
            'header' =>'total price',// total price doesn't save in Data Base
            'name'=>'total_price',
            'value'=>'total_price - (total_price * $data->discount/100)',
    ),
    array(
        'class'=>'CButtonColumn',
    ),
),

));
?>

4

1 回答 1

0

您可以使用 $model->search() 方法:

$criteria=new CDbCriteria;

$criteria->select = "t.*, t.price - (t.price * t.discount/100) as total_price";

// EDITED: Added for Sort:
$sort = new CSort();
$sort->attributes = array(
                        'defaultOrder'=>'name ASC',
                        'total_price'=>array(
                            'asc'=>'total_price ASC',
                            'desc'=>'total_price DESC',
                          ),
                          '*', // Add order in the other fields.
                    );

return new CActiveDataProvider($this, array(
        'criteria'=>$criteria,
        'sort'=>$sort, // Added to sort.
);

并在“产品”模型类上创建一个非持久性属性:

public $total_price;

最后将 'total_price' 放在带有 ('safe', 'on'=>'search') 的数组中的 rules() 上,如下所示:

array('id, name, price, discount, total_price', 'safe', 'on'=>'search'),
于 2013-08-05T10:24:01.490 回答