I am using PHP Yii and try to display a value that were derived from the value saved in database.
Here is my model
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');
}
View- index
<!-- 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!
),
),
As you can see,I had set an getTradetype method in the model for the mapping relation. I tried to make the code clean. But I thought there might be some better solution for the dropdownlist case.As for the Cgridview case, my code did not work at all. Thanks.
for the grid view, change you function to return string, not array
public function getTradetype(){
$types = array('1' => 'Buy', '2' => 'Sell');
return isset($types[ $this->type ]) ? $types[ $this->type ] : 'undefined';
}
if you want default name of the variable in the header, you don't need to specify it in the array, value and name would be enough, I think you didn't set the name properly
As an alternative to Tinybyte's answer , I usually put the relation as an array and use a function similar to his/her answer.
public static $tradeTypes = array('1' => 'Buy', '2' => 'Sell');
...
public function getTradeType() {
return isset(self::$tradeTypes[ $this->type ]) ? self::$tradeTypes[ $this->type ] : 'undefined';
}
This makes it possible to use TradeRecord::tradeTypes
as the dropdown list's options and tradeType
as the value
for the grid view.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.