为Yii2创建multi_models注册页面并在会话中保存该信息

时间:2016-11-22 20:46:58

标签: php session yii2

我正在开发一个个人的Yii2项目而且我被卡住了!我不知道如何:

  • 创建一个单一页面,其中包含一个表单,用于创建两个相关模型(Organization& Employee)并使用第三个模型(Employee_Role)
  • 将这些信息存储在会话中,稍后再使用该会话。

一般情景:

通过填写管理员注册: 组织名称 和用户名&密码&电子邮件(适用于管理员工)

如果值有效,则系统创建"组织"使用auto_generated organization_id。

然后,系统创建"员工" (需要organization_id并将此用户分配给Admin" Employee_Role")

然后,系统在会话中保留以下信息:(organization_id,employee_id,role_id,timestamp)并将用户带到管理主页。

注意,我将模型保存在Common文件夹中,而控制器保留在前端,因此应该是视图。

感谢您的帮助,

1 个答案:

答案 0 :(得分:0)

这是您可以采取哪些措施来解决问题。您需要将实际字段添加到组织和员工的表单中。

控制器操作:

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() ?>
相关问题