Creating a Drop Down List using Constants
In designing databases often time we will use integers to represent data such as 'status' for example rather than actually storing "Created/In Progress/Completed". This is fine however when it comes to entering data into your view you have to know that 1 = In Progress, 0 = Created. It would be easier if you could have a drop down list. With Yii it is not difficult to achieve just that.
The first thing you need to do is create these constants in the Model. Let us assume we have a model called 'Job'. In the Job model create the constants you require.
class Job extends CActiveRecord
{
const STATUS_CREATED=0;
const STATUS_PROGRESS=1;
const STATUS_COMPLETED=2;
public function getStatus()
{
return array (
self::STATUS_CREATED=>'Created',
self::STATUS_PROGRESS=>'In Progress',
self::STATUS_COMPLETED=>'Completed',
);
}
<div class="wide form">
.......
<div class="row">
<?php echo $form->labelEx($model,'status'); ?>
<?php echo $form->dropDownList($model, 'status', $model->getStatus()); ?>
<?php echo $form->error($model,'status'); ?>
</div>
If you open up the form you will notice that there is a drop down list populated by Created/In Progress/Completed. When you save the form the value of 0,1 or 2 is written to the database........
<div class="row">
<?php echo $form->labelEx($model,'status'); ?>
<?php echo $form->dropDownList($model, 'status', $model->getStatus()); ?>
<?php echo $form->error($model,'status'); ?>
</div>
You can take this a step further. Continuing with the example of a model called Job you should be able to list a specific job in your view and instead of the Status displaying a value of 0, 1 or 2 you can output the corresponding text. The way to do this is to create an additional function inside the Job model.
public function getActiveStatusText ()
{
$activeStatus=$this->getActiveStatus();
return isset($activeStatus[$this->status]) ? $activeStatus[$this->status] : "unkown status({$this->status})";
}
<?php $this->widget('bootstrap.widgets.TbDetailView', array(
'type'=>'striped bordered condensed',
'data'=>$model,
'attributes'=>array(
'job_name',
'username',
array(
'name'=>'status',
'value'=>CHtml::encode($model->getActiveStatusText()),
),
),
)); ?>
References:
1 comment:
In our Agency we use yii and we think it's really amazing. It helps to speed up development without losing quality.
Thank for this post!
Post a Comment