Inserint MANY_MANY data from CheckBoxList


I lost 4 hours trying to do this by searching the forum, but unsuccessfully.

This is my table structure:

+--------------+     +-------------------+     +------------+

| categoria    |     | categoria_contato |     | contato    |

+--------------+     +-------------------+     +------------+

|*id_categoria |<<<<<|*id_categoria      |  |>>|*id_contato |

|nome          |     |*id_contato        |>>|  |nome        |

+--------------+     +-------------------+     +------------+

In the model of ‘categoria’, there is the following relationship:

'contatos' => array(self::MANY_MANY, 'Contato', 'categoria_contato(id_categoria, id_contato)'),

And in the model of ‘contato’, there is the follow:

'categorias' => array(self::MANY_MANY, 'Categoria', 'categoria_contato(id_contato, id_categoria)'),

On the file ‘_form’ in ‘contato’, got the following:

echo $form->checkBoxList($model, 'categorias', CHtml::listData(Categoria::model()->findAll(array('order' => 'nome')), 'id_categoria','nome'));

I thought it would Yii automatic, as it is put into $ _POST [‘Contato’] a field called ‘categorias’ marked with the ids:


  array(6) {


    string(1) "6"


    string(2) "16"


    string(1) "8"


    string(2) "13"


    string(1) "4"


    string(2) "15"


What is missing to make the Yii inserts on table ‘categoria_contato’?

Can anyone help me?

Might this plugin work for you?

Ok, thanks.

But I would not want to use something that is out of Yii.

I would use the native resources framework.

How could I do this using the framework?

Do I have on hand, the method afterSave()?!

Best regards!

I’m working on the same issue, and would also like to learn to do this the way Yii intends. When I implement the model Rafael describes above, I get the error:

Object of class EldCategory could not be converted to int

where EldCategory is the model my MANY_MANY relation, categories, points to.

Hello friend…

You need implement in your controller, on the ‘loadModel’ method, the follow:


if($model!==null) {

	$criteria = new CDbCriteria();

	$criteria->select = 'id_categoria';

	$criteria->condition = 'id_contato = ' . $id;

	$catCons = CategoriaContato::model()->findAll($criteria);

	$ids = array();

	foreach($catCons as $catCon) {

		array_push($ids, $catCon->id_categoria);


	$model->categorias = $ids;


It does Yii select checkboxies that are store in database…

best regards

This can be done using one of the available behaviors, since with Yii would have to do it all manually.

These behavior add axtra functionality to your activeRecord models, check out this one for example: