how to add data from Employee table to user table in YII2 advanced

426 views Asked by At

I am working on my collage project i.e. Employee Management. I have Employee table in sql(crud is also generated from gii). only Admin is having rights to create Employee (there is no Signup).

My Problem: when I am creating employee then I am not able to save data in user table also, please help me to save data in both Employee and user table.

Thanks in advance

Update:

Below is the code:

public function actionCreate() { 
 $model1=new Employee; 
 $model2=new User; 
 if(isset($_POST['Employee']) && isset($_POST['User']))
 { 
   $model1->attributes=$_POST['Emoloyee']; 
   $model2->attributes=$_POST['User']; 
   $model1->save(); 
   $model2->save(); 
   echo 'data is saved in both tables'; 
 } 
 $this->render('create',array('model1'=>$model1,model2'=>$mod‌​‌​el2)); 
}
3

There are 3 answers

0
Radhe9254 On
3
Insane Skull On

You can try this example,

public function actionCreate()
{
    $model = new Employee(); 
    $user = new User(); 

    if ($model->load(Yii::$app->request->post()) && $user->load(Yii::$app->request->post())) {

        if($model->save() && $user->save()) {
            Yii::$app->session->setFlash('success', 'Record saved successfully.');
        } else {
            //var_dump($model->getErrors());
            //var_dump($user->getErrors());
            Yii::$app->session->setFlash('error', 'Record not saved.');
        }

        return $this->redirect(['index']);
    } else {
        var_dump($model->getErrors());
        var_dump($user->getErrors());
        die();
    }
    return $this->render('create', [
        'model' => $model,
        'user' => $user,
    ]);
}
2
ScaisEdge On

could be you have some validation problem

try check this way

    ......

    $model1->attributes=$_POST['Emoloyee']; 
    $model2->attributes=$_POST['User']; 

    if ($model1->validate() && $model2->validate() ) {
        $model1->save(); 
        $model2->save(); 


    } else {
         $errors1 = $model1->errors;
         $errors2 = $model2->errors;
         var_dump($errors1);
         var_dump($errors2);
         exit();

    }

then just for debug try using

    $model1->attributes=$_POST['Emoloyee']; 
    $model2->attributes=$_POST['User']; 
    $model1->save(false);
    $model2->save(false);  

and check in db if the value are saved ..