我正在使用PHP Yii,并尝试显示从保存在数据库中的值派生的值。
这是我的模型
Model-TradeRecord
public type; //Type:'1' means Buy,'2' means Sell. $model->type is get from database
public function attributeLabels(){
return array(
/* some attribute */
'type'=>'Trade Type' //This is also the column header
}
public function getTradetype(){
return array('1' => 'Buy', '2' => 'Sell');
}
视图——指数
<!-- dropdown list-->
<?php echo CHtml::dropDownList('TradeRecord[type]', $model->type, //any better solution?
$model->tradetype,
array('empty' => '(select..)','class'=>'form-control'));
?>
<!--CgridView column-->
<?php $this->widget('bootstrap.widgets.BsGridView', array(
'id'=>'trade-record-grid',
'dataProvider'=>$dp,
'columns'=>array(
array(
'header' => '$data->getAttributeLabel("type")', //not worked!
'name'=>'type',
'value'=>'($data->tradetype($data->type))', //not worked!
),
),
可以看到,我在映射关系的模型中设置了一个getTradetype方法。我试着让代码简洁。但我认为对于下拉列表的情况可能有更好的解决方案。至于Cgridview的情况,我的代码根本不起作用。谢谢。
对于网格视图,将函数更改为返回字符串,而不是数组
public function getTradetype(){
$types = array('1' => 'Buy', '2' => 'Sell');
return isset($types[ $this->type ]) ? $types[ $this->type ] : 'undefined';
}
如果你想在header中指定变量的默认名称,你不需要在数组中指定它,value和name就足够了,我认为你没有正确设置名称
作为Tinybyte的答案的替代方案,我通常将关系作为数组并使用与他/她的答案相似的函数。
public static $tradeTypes = array('1' => 'Buy', '2' => 'Sell');
...
public function getTradeType() {
return isset(self::$tradeTypes[ $this->type ]) ? self::$tradeTypes[ $this->type ] : 'undefined';
}
这使得可以使用TradeRecord::tradeTypes
作为下拉列表的选项,tradeType
作为网格视图的value
。