這是你可以做什麼來解決你的問題概要。您需要將實際字段添加到組織和員工的表單中。
控制器動作:
public function actionSignup() {
$post = Yii::$app->request->post();
$organization = new Organization();
$employee = new Employee();
// we try to load both models with the info we get from post
if($organization->load($organization) && $employee->load($organization)) {
// we begin a db transaction
$transaction = $organization->db->beginTransaction();
try {
// Try to save the organization
if(!$organization->save()) {
throw new \Exception('Saving Organization Error');
}
// Assign the organization id and other values to the employee
$employee->organization_id = $organization->id;
...
// Try to save the employee
if(!$employee->save()) {
throw new \Exception('Saving Employee Error');
}
// We use setFlash to set values in the session.
// Important to add a 3rd param as false if you want to access these values without deleting them.
// But then you need to manually delete them using removeFlash('organization_id')
// You can use getFlash('organization_id'); somewhere else to get the value saved in the session.
Yii::$app->session->setFlash('organization_id', $organization->id)
Yii::$app->session->setFlash('employee_id', $employee->id)
...
// we finally commit the db transaction
$transaction->commit();
return $this->redirect(['somewhere_else']);
}
catch(\Exception e) {
// If we get any exception we do a rollback on the db transaction
$transaction->rollback();
}
}
return $this->render('the_view', [
'organization' => $organization,
'employee' => $employee,
]);
}
視圖文件:
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
?>
<?php $form = ActiveForm::begin() ?>
<?= $form->field($organization, 'some_organization_field') ?>
<!-- More Fields -->
<?= $form->field($employee, 'some_employee_field') ?>
<!-- More Fields -->
<?= Html::submitButton('Save', ['class' => 'btn btn-primary']) ?>
<?php ActiveForm::end() ?>
幫助很大,謝謝 –