Render Array

Hi to all. I have a table Cars and Options. Just created a table Cars_Options. In the relations of Cars model i set that the:


'services'=>array(self::MANY_MANY, 'Options','Cars_options(cars_id, options_id)')


With which widjet i can render $model->options array in Cars view?

I just want to use widjet to display Cars related Options.

I have no idea how to display an array :rolleyes: . It sims simple but i dont know how to do this simple thing.

I try to render it by

<?php for($i=0;$i<2;$i++){

    echo $model->options[$i]->option."<br>";



But i think there must be an easier and more corect way.

You could do:

foreach( $model->options as $option) {

echo $option  . '<br/>';


Use the PHP docs.

No, seriously: they are great.

And you can find lots of nice tips in the comments. :)


Thanks for reply. I know that i can do it by using for or foreach cycle. But is there any way to do it with widget?

Oh, right.

Create a widget:

class CarOptions extends CWidget {

	public $options = null;

	public function getOptions() {

    	return (isset($this->options) ? $this->options : array());


	public function run() {

// this method is called by CController::endWidget()




Then, in the directory of the widget, create a directory called ‘views’ and put this in it:

<?php foreach($this->getOptions() as $option) : ?>


<?php echo $option; ?>


<?php endforeach; ?>

It should be named ‘carOptions.php’.

Then, in your Car view:

<?php $this->widget('CarOptions', array('options' => $options)); ?>

Not tested by me, but it shows one possible way of doing it.

Ok. Its cool. But is there any way to use standar widgets? Like: CListView or CGridView.

You can use anything in a widget.

Think of it as a mini-controller with it’s own view. ;)

Ok. Another question: i’m using many to many relation. Options of car i’m setting via using checkboxlist. How can i update cars_options table with selected id?

Look into CHtml::listData which can be used to generate the $options array for dropdownbuttons, checklistsboxes, etc.

CHtml::CheckBoxList('Options', null, CHtml::listData(CarOptions::model()->findAll(), 'id', 'name')