Use the CAdvacedArBehavior in your Book model, and create a public variable
$authorIds = array();
in your Book model… then in afterFind:
public function afterFind() {
$this->authorIds = array_keys(CHtml::listData($this->Authors, 'id', 'name'));
return parent::afterFind();
}
in your form just use activeCheckBoxList with the newly introduced authorIds instead of the author relation (if needed enter it in attributeLabels aswell).
Then either in Controller after mass assignment of the attributes you just do:
$model->Authors = $_POST[‘Book’][‘authorIds’];
or write a magic getter / setter for it and add it as a safe attribute.
public function actionUpdate($id)
{
$model=$this->loadModel($id);
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['Book']))
{
$model->attributes=$_POST['Book'];
$model->authors = $_POST['Book']['authorIds'];
$model->setAttribute('authors', '23');
and:
1/ model->authors is:
Array
(
[0] => 1
[1] => 2
[2] => 3
)
it’s OK data from POST.
2/ $model->setAttribute(‘authors’, ‘23’); doesn’t work. I haven’t attribute “authors”.
3/ save() method don’t see $model->authors and don’t save it.
public function afterSave() {
$command=Yii::app()->db->createCommand('
DELETE FROM book_has_author WHERE book_id = '.$this->id)->execute();
foreach ($this->authors as $author) {
$command = Yii::app()->db->createCommand("
INSERT INTO book_has_author (book_id, author_id) VALUES ($this->id, $author->id)")->execute();
}
}