Recommended/nicest way for multiple attributes in listData/DropDownList

Hi,

Presume a very basic form with a list part like this:

<?php echo CHtml::activeDropDownList($model, ‘customer_id’, CHtml::encodeArray(CHtml::listData(Customer::model()->findAll(), ‘id’, ‘first_name’))); ?>

Let’s say we need to make the text attribute in the list consist of both first_name and last_name from the Customer model. What is the recommended/Yii way to do that?

Searching the forums it looks doable either by giving a manual criteria to the model argument of listData (which would feel a bit misplaced, maybe a scope or something would be nicer), or by the addition of an extra field on the model in question. If the latter case is the preferred one, what changes would be needed to the model?

Thanks!

In the model:




private $fullName;


public function getFullName()

{

    return $this->first_name.' '.$this->last_name;

}



In the view:




<?php echo CHtml::activeDropDownList($model, 'customer_id', CHtml::encodeArray(CHtml::listData(Customer::model()->findAll(), 'id', 'fullName'))); ?>



Sounds good :)

Is there no need to have a setter for this “virtual” property though? I don’t have the need to write the property myself, but I’m thinking that maybe the Model or AR or something would try to save/update it at some point, simply because it finds the property in the model class.

Also, is the declaration really needed and not just the getter? As I understand it, the getter is what is called in the end anyway, when the property is requested.

No, AR won’t try to save it since this field is not in the table schema.

And yes, you can leave only getter, and everything should work.

OK, cool.

I thought about that property && getter vs just getter. It might actually be a good idea to declare all the properties, even those that are "virtual". Otherwise one would have to search getters to know what properties there are, not a good thing.

Hi Andy,

Thanks, it worked for me. I have a more fundamental question.

You never mention $fullname variable in getter function, how does Yii figure out to return $fullname? Also it looks really strange how findAll() can figure out to go to model and call getter function and build fullname. Normally in PHP this doesn’t work, is that right?

Read this.

http://www.yiiframework.com/wiki/167/understanding-virtual-attributes-and-get-set-methods/