I have a many to many relation between User and Group.
In a form to update the User I can retrieve the groups with $User->groups; This returns an array of ActiceRecord objects. When the user writes invalid data into the form, then the form is displayed again but now the array returned by $User->groups contains the ids of the groups not the group objects. Is this a bug or a feature and how can I solve this?
<?php
class User extends CActiveRecord
{
public static function model($className=__CLASS__)
{
return parent::model($className);
}
public function tableName()
{
return 'user';
}
public function rules()
{
return array(
// ...
array('groups, user_id, group_id', 'safe'),
);
}
public function relations()
{
return array(
'groups'=>array(self::MANY_MANY, 'Group',
'user_group(user_id,group_id)'),
);
}
public function behaviors()
{
return array('CAdvancedArBehavior',
array('class' => 'ext.CAdvancedArBehavior')
);
}
}
<?php
class UserController extends Controller
{
// ...
public function actionUpdate()
{
$model=$this->loadModel();
$this->performAjaxValidation($model);
if(isset($_POST['User']))
{
$model->attributes=$_POST['User'];
if($model->save())
$this->redirect(array('admin'));
}
$this->render('update',array(
'model'=>$model,
));
}
public function loadModel()
{
if($this->_model===null)
{
if(isset($_GET['id']))
$this->_model=User::model()->findbyPk($_GET['id']);
if($this->_model===null)
throw new CHttpException(404, Yii::t('app', 'The requested user does not exist.'));
}
return $this->_model;
}
protected function performAjaxValidation($model)
{
if(isset($_POST['ajax']) && $_POST['ajax']==='user-form')
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
}
}
<?php
// form
//var_dump($model->groups);
$AllGroups = Group::model()->findAll();
$aAllGroups = array();
foreach ($AllGroups as $Group)
$aAllGroups[$Group->id] = $Group->name; // name is a virtual (translated) property
asort($aAllGroups);
$aSelectedGroups = array();
foreach ($model->groups as $Group) {
// workaround ...
if (!is_object($Group))
$Group = Group::model()->findByPk($Group);
$aSelectedGroups[] = $Group->id;
}
<?php foreach($aAllGroups as $iId => $sLabel) { ?>
<div class="row">
<label><?php echo CHtml::checkbox("User[groups][]", in_array($iId, $aSelectedGroups), array('value' => $iId)); ?> <?php echo CHtml::encode($sLabel); ?></label>
</div>
<?php } ?>
// some other fields