CHtml :: listData with complex $ textField

I would like to use a couple of attributes from the model as a textField . Something like that:

 $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)' automatically converted to the correct attribute values. I tried to write "as is" ( 'attribute1 attribute2 (attribute3)' ) and create a middle function inside the model ( fullName() ), but nothing worked.

Thanks in advance.

+6
source share
2 answers

This is possible by creating an additional method in your model class. You must create a getter and use it with yii magic as a regular 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.')'; } 
+11
source

If you have PHP versions greater than 5.3, 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() ); 
+1
source

Source: https://habr.com/ru/post/910695/


All Articles