Mohammad
Mohammad

Reputation: 3547

how to fill 2 models in one action

hello guys, i have 2 models Users and Communities, i want to fill some data into the model Communities by using the actionCreate of the model Users, but there is nothing saved in the model communities, here is my code :

public function actionCreatec()
    {
            if($this->actionlogged()==0||$this->actionisadmin()==1)
            {
        $model=new Users;
                $model2=new Communities; 

        // Uncomment the following line if AJAX validation is needed
        $this->performAjaxValidation($model);
        if(isset($_POST['Users']))
        {

                    $model->attributes=$_POST['Users'];
                    $model2->idUser=$model->idUser;
                    $model2->admin=1;
                    $model2->save();
                    $model->userType='c';
                    $model->gender='n';
                    $model->firstName='null';
                    $model->lastName='null';
                    $model->birthDate='null';
                    $model->active=1;
                    $model->admin=0;

                    if(isset($_POST['profile'])==0)
                        $model->profilePhoto='default.jpg';
                    elseif(isset($_POST['profile'])==1)
                        $model->profilePhoto=CUploadedFile::getInstance($model,                'profilePhoto');

                    if($model->save()){
                        $this->actionfiledir();
                        if(isset($_POST['profile'])==1)
                            $model->profilePhoto->saveAs($this->actionphotodir()."/".$model->profilePhoto);
                        Yii::app()->session['userId']=$model->idUser;
                        $this->redirect(array('view','id'=>$model->idUser));
                    }
                }

        $this->render('createc',array(
            'model'=>$model,
        ));
            }
            else
                $this->redirect(array('site/index'));
    }

Upvotes: 1

Views: 81

Answers (1)

Hubu
Hubu

Reputation: 59

$model2 probably can't pass validation. You can check if $model2->save(); returns false, and $model2->getErrors() (do it after save method) to see validation errors.

To skip validation:

$model2->save(false);

Upvotes: 1

Related Questions