doumianfeng6979 2013-01-15 20:26
浏览 48
已采纳

Yii GetStatus()

My User Model have 3 Status options (Active, Deleted, Blocked). When seeing it in the view it shows as numbers 1, 2 or 3. What I can do to show it by the status name?

Model.php

const STATUS_ACTIVE = 1;
const STATUS_DELETED = 2;
const STATUS_BLOCKED = 3;

Controller.php

public function actionAdmin()
{
    $model=new Users('search');
    $model->unsetAttributes();  // clear any default values
    if(isset($_GET['Users']))
        $model->attributes=$_GET['Users'];

    $this->render('admin',array(
        'model'=>$model,
    ));
}

View.php

<?php $this->widget('bootstrap.widgets.TbGridView',array(
    'type'=>'striped bordered condensed',
    'id'=>'users-grid',
    'dataProvider'=>$model->search(),
    'filter'=>$model,
    'columns'=>array(
        'name',
        'status', // Show 1,2 or 3. I want to get the status name.
    ),
)); ?>
  • 写回答

1条回答 默认 最新

  • douzi6060 2013-01-15 20:46
    关注

    Create a new method in your User model called getStatusName that returns the status name. Here is one possible way of doing it:

    public function getStatusName()
    {
        switch($this->status)
        {
            case self::STATUS_ACTIVE:
                return 'Active';
                break;
    
            case self::STATUS_DELETED:
                return 'Deleted';
                break;
    
            case self::STATUS_BLOCKED:
                return 'Blocked';
                break;
    
            default:
                return 'Unknown';
                break;
        }
    
    }
    

    Then in your CGridView, do this:

    <?php $this->widget('bootstrap.widgets.TbGridView',array(
        'type'=>'striped bordered condensed',
        'id'=>'users-grid',
        'dataProvider'=>$model->search(),
        'filter'=>$model,
        'columns'=>array(
            'name',
            'statusName' // And let Yii do its magic OR be explicit
            array('name' => 'status', 'type' => 'text', 'value' => '$data->statusName'),
        ),
    )); ?>
    

    Note: if you used the short version on the column configuration, you should add statusName to your attributeLabels array

    //model.php
    public function attributeLabels(){
      return array(
        //Other labels
        'statusName' => 'status',
      )
    }
    

    This way you can also use the same attribute in other places, and let it behave like a normal attribute (only that it is read-only).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助