Multiple attributes in CHtml::listData()

Hi all

The following produces a dropdown list with ‘id’ as the value and ‘name’ as the name:


<?php echo $form->dropDownList($model,'MyAttribute',CHtml::listData(OtherModel::model()->findAll(), 'id', 'name')); ?>

However, I would like to produce a list with ‘id’ as the value and ‘name (othername)’ as the name. I have tried the following, but this doesn’t work:


<?php echo $form->dropDownList($model,'MyAttribute',CHtml::listData(OtherModel::model()->findAll(), 'id', 'name'.'(othername)')); ?>

Is this possible?

Many thanks.

Yep it’s possible, you just have to do it a little differently. First add a function to your model to get the data:


//OtherModel.php

public function getNameOtherName()

{

    return $this->name.' ('.$this->othername.')';

}



Now you can do this in your form:




<?php echo $form->dropDownList($model,'MyAttribute',CHtml::listData(OtherModel::model()->findAll(), 'id', 'nameOtherName')); ?>



Excellent, thanks lgoss007!

It now makes sense that I should be doing the concatenation in the model rather than the view.