问题
this is my create page questions/create.php
`
<?= $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(); ?>
`
Employee Controller
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,
]);
}
}
i have migrated user table and also included class in the controller but the data is not inserting in the user table (only in Employee table) what would be the possible way.
Acutely in advanced yii2 users can login from user table so I want data from employee table to send to user table also.
if there is any other better way so that employee can be created and logged in
回答1:
Add the following code to to your create action
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,
]);
}
}
Now in your form write the attribute and model which are related,like suppose first_name and last_name from Employee model and password ans email from user model then
<?= $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]) ?>
来源:https://stackoverflow.com/questions/46173865/how-to-insert-data-to-2-tables-i-e-employee-and-usermigrated-from-single-form