CHtml::listData Modified

Hi there,

I saw a couple of times at the forum people asking how to concatenate two attributes for the CHtml::listData method and I am currently developing a customized CHtml extension to render HTML elements properly for my new CMS that has that function modified. I post it here, so you guys can make use of it for your own needs.

I think that could be a good section in the forum for developers to share their functions (pieces of code too small to write a wiki or a extension). Things that maybe useful for others to ‘plug’ onto their Yii resource libraries. Anyway, whatever the team does I am sure they will do good.

Here is this little and useful function (at least for me).




/**

* 

* Modified CHtml listData

* @param array $models

* @param string $valueField 

* @param array|string $textFields 'attribute' or array('attribute1','attribute2')

* @param string $groupField

*/

public function listData( $models, $valueField, $textFields, $groupField = '' ){

		

		$listData=array();

		

		foreach($models as $model)

		{

			$value=CHtml::value($model,$valueField);

			if(is_array($textFields)){

				$text = array();

				foreach($textFields as $attr){

					$text[]= CHtml::value($model,$attr);

				}

				$text = implode(' ', $text);

			}

			else

				$text= CHtml::value($model,$textFields);

			

			if($groupField===''){

				$listData[$value]=$text;

			}

			else{

				$group=CHtml::value($model,$groupField);

				$listData[$group][$value]=$text;	

			}

				

		}

		return $listData;

	}



Thank you so much for providing this function. I was stuck this issue last 5 to 6 hour. I was not getting any proper solution. But when i applied these function, i got a proper result which i wanted.

Antonio!!!!

Encarecidamente muchas gracias por compartir tan acertada solución!!!

Antonio,

You solve this in such a simple manner! Thank you!

hi friends you can use like this

$criteria = new CDbCriteria;

	$models = modelname::model()->findAll($criteria);


	


	$list = CHtml::listData($models, 'id', 'title');


	


	return $list;