6

I'd like to use a couple of attributes from within a model as textField. Something like this:

$form->dropDownList(
    $formModel, 
    'ref_attribute', 
    CHtml::listData(
        User::model()->findAll(array('order'=>'attribute1 ASC, attribute2 ASC')), 
        'id', 
        'attribute1 attribute2 (attribute3)'), 
    array()
);

so that 'attribute1 attribute2 (attribute3)' is automatically translated into the correct attribute values. I have tried writing it "as is" ('attribute1 attribute2 (attribute3)'), and creating a middle function inside the model (fullName()), but nothing seemed to work.

Thanks in advance.

zishe
  • 10,665
  • 12
  • 64
  • 103
Sergi Juanola
  • 6,531
  • 8
  • 56
  • 93

2 Answers2

11

It is possible by creating a extra method in your Model class. You have to create a getter and use it with the yii magic as a normal property.

So you have in your template:

$form->dropDownList(
    $formModel, 
    'ref_attribute', 
    CHtml::listData(
        User::model()->findAll(array('order'=>'attribute1 ASC, attribute2 ASC')), 
        'id', 
        'fullName'), 
    array()
);

And in your model:

public function getFullName()
{
    return $this->attribute1.' '.$this->attribute2.' ('.$this->attribute3.')';
}
ews2001
  • 2,176
  • 3
  • 26
  • 38
cebe
  • 3,610
  • 1
  • 23
  • 37
1

If you have PHP of version greater than 5.3 then you can use anonymous functions:

$form->dropDownList(
    $formModel, 
    'ref_attribute', 
    CHtml::listData(
        User::model()->findAll(array('order'=>'attribute1 ASC, attribute2 ASC')), 
        'id', 
        function($model){
            return $model->attribute1.' '.$model->attribute2.' ('.$this->attribute3.')';
        }
    ), 
    array()
);
Radu Dumbrăveanu
  • 1,266
  • 1
  • 22
  • 32