Insert Into Table Many To Many Relationship Using A Form

hi guys, I am a beginner with yii framework.

I have two objects: user and project, both linked by many to many relationship and I would like to create a form to add user to a project.

I’ve spend more time to find out solution about it, and finally, the codes bellow still work well.

this is my view form:




<?php

    $this->breadcrumbs=array(

	'Project'=>array('index'),

        'Add Member',

);

?>

<h3>Add Member for : <?php echo $project->name; ?> Project</h3>

<div class="form">

    <?php $form=$this->beginWidget('CActiveForm'); ?>


        <?php echo $form->errorSummary($project); ?>


        <div class="row">

            <?php echo $form->label($project,'User List'); ?>

            <?php echo $form->hiddenField($project,'idproject', array('required'=>'required')) ?>

            <?php echo CHtml::dropDownList('listusername', $user, $list, array('empty'=>'select user','multiple'=>true));?>

        </div>


        <div class="row submit">

            <?php echo CHtml::submitButton($project->isNewRecord ? 'Create' : 'Save'); ?>

        </div>


    <?php $this->endWidget(); ?>

</div><!-- form -->



And these are 2 functions to add user to a project:




public function newUser($project)

         {

            $user = User::model()->findAll();

            

            if(isset($_POST['Project']))

            {

                var_dump($_POST);die();

                $project->attributes=$_POST['Project'];

                foreach ($_POST['listusername'] as $lu){

                    $u[] = User::model()->findByPk((int)$lu);

                }

                    $project->users = $u;

                    $project->withRelated->save(true, array('users'));

       

            }

            return $user;

         }

        

         public function actionAddTeamProject($id){

            $project = Project::model()->findByPk($id);

            $user = $this->newUser($project);

            $list = CHtml::listData($user, 'iduser', 'username');

            

            $this->render('addTeam',array(

                'project'=>$project, 

                'user'=>$user,

                'list'=>$list,

                )

            );

        }



I don’t know if I did well. So my question is: Is there another way to do that?

Thanks! :wink: