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.
),
)); ?>
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).