这是我的创建页面 问题/ 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(); ?>
`
员工控制器
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 :(得分: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,
]);
}
}
现在在您的表单中编写相关的属性和模型,例如假设来自Employee模型的first_name和last_name以及来自用户模型的密码和电子邮件
<?= $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]) ?>