Friday, November 30, 2012

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;

You now need to create a function to get the constants and again create this function in your model.

public function getStatus()
{
return array (
self::STATUS_CREATED=>'Created',
self::STATUS_PROGRESS=>'In Progress',
self::STATUS_COMPLETED=>'Completed',
);
}
All that is required now is to create a drop down list in your view. To do this you can take advantage of Yii's build in dropDownList.
<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.
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})";
}
Then to use this in your view (e.g. CDetailView or Bootstraps TbDetailView)

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

That's all there is to it. There are other methods for creating this functionality however I find this the easiest and quickest to implement.

References:

  1. Understanding Virtual Attributes and get/set methods 
  2. Managing constants easily



1 comment:

Unknown said...

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!