2017-09-12 15 views
-1

這是我創建頁面 問題/ create.php如何將數據插入到2個表,即員工和用戶(遷移)從單一形式(員工創建)和控制器yii2

`

<?= $form->field($model, 'clinic_id')->dropDownList(
     ArrayHelper::map(Clinic::find()->all(),'id','clinic_name'), 
     ['prompt'=> 'Select Clinic'] 
     )?> 

<?= $form->field($model, 'first_name')->textInput(['maxlength' => true]) ?> 

<?= $form->field($model, 'last_name')->textInput(['maxlength' => true]) ?> 

<?= $form->field($model, 'user_name')->textInput(['maxlength' => true]) ?> 

<?= $form->field($model, 'password')->passwordInput(['maxlength' => true]) ?> 

<?= $form->field($model, 'email')->textInput(['maxlength' => true]) ?> 

<?= $form->field($model, 'mobile')->textInput(['maxlength' => true]) ?> 

<?= $form->field($model, 'is_active')->textInput() ?> 

<div class="form-group"> 
    <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?> 
</div> 

<?php ActiveForm::end(); ?> 

`

員工控制器

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

    if ($model->load(Yii::$app->request->post()) && $model->save()) { 
     return $this->redirect(['view', 'id' => $model->id]); 
    } else { 
     return $this->render('create', [ 
      'model' => $model, 
     ]); 
    } 
} 

我已移居美國呃表和控制器中也包含類,但數據沒有插入到用戶表中(僅在Employee表中),可能的方式是什麼。

先進的yii2用戶可以從用戶表登錄,所以我想從員工表的數據發送到用戶表也。

如果有任何其他更好的辦法,以便可以創建該員工,並記錄在

回答

0

下面的代碼添加到您的創建操作現在

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

    if($user->load(Yii::$app->request->post()) AND $employee->load(Yii::$app->request->post()) AND Model::validateMultiple([$user, $employee])) { 
    if($user->save(false) AND $employee->save(false)) 
    { 
     return $this->redirect(['index']); 
    } 
    else{ 
     return $this->render('create', [ 
     'employee' => $employee, 'user' => $user, 
    ]); 
    } 

    } 
    else { 
    return $this->render('create', [ 
    'employee' => $employee, 'user' => $user, 
    ]); 
    } 
} 

在你的形式寫出屬性和模型,是相關的,如假設first_name和last_name從僱員模型和密碼ans用戶模型的電子郵件然後

<?= $form->field($employee, 'first_name')->textInput(['maxlength' => true]) ?> 

<?= $form->field($employee, 'last_name')->textInput(['maxlength' => true]) ?> 

<?= $form->field($user, 'user_name')->textInput(['maxlength' => true]) ?> 

<?= $form->field($user, 'password')->passwordInput(['maxlength' => true]) ?> 

<?= $form->field($user, 'email')->textInput(['maxlength' => true]) ?> 
+0

非常感謝我能夠保存用戶表中的所有細節。我現在的問題是,我不能以散列格式保存密碼,你能幫我嗎 –

+0

檢查你是否在控制器獲取密碼?如果是,那麼上面的代碼將生成哈希碼。否則,使用自定義哈希生成代碼,如$ user-> password = Yii :: $ app-> getSecurity() - > generatePasswordHash($ password); $ user-> repeat_password = Yii :: $ app-> getSecurity() - > generatePasswordHash($ password); 。如果($ user-> save(false)AND $ employee-> save(false))寫上這段代碼 – Radhe9254

相關問題