【问题标题】:How to change the display value of an model attributes in Yii dropDownList and Cgridview?如何更改 Yii dropDownList 和 Cgridview 中模型属性的显示值?
【发布时间】:2014-06-03 02:48:04
【问题描述】:

我正在使用 PHP Yii 并尝试显示从保存在数据库中的值派生的值。

这是我的模型

模型交易记录

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 的情况,我的代码根本不起作用。 谢谢。

【问题讨论】:

    标签: php yii


    【解决方案1】:

    对于网格视图,将函数更改为返回字符串,而不是数组

    public function getTradetype(){
        $types = array('1' => 'Buy', '2' => 'Sell');
        return isset($types[ $this->type ]) ? $types[ $this->type ] : 'undefined';
    }
    

    如果你想在表头中设置变量的默认名称,你不需要在数组中指定它,值和名称就足够了,我认为你没有正确设置名称

    【讨论】:

      【解决方案2】:

      作为Tinybyte's answer 的替代方案,我通常将关系作为一个数组并使用类似于他/她的答案的函数。

      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 成为可能。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多