Inserint MANY_MANY data from CheckBoxList

Hello!

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:


["categorias"]=>

  array(6) {

    [0]=>

    string(1) "6"

    [1]=>

    string(2) "16"

    [2]=>

    string(1) "8"

    [3]=>

    string(2) "13"

    [4]=>

    string(1) "4"

    [5]=>

    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?

http://www.yiiframework.com/extension/save-relations-ar-behavior/

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:




$model=Contato::model()->findByPk((int)$id);

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:

http://www.yiiframework.com/extension/esaverelatedbehavior/