2016-11-22 73 views
0

我正在个人Yii2项目上工作,我被卡住了!我不知道如何:为Yii2创建multi_models注册页面并在会话中保存该信息

  • 创建一个唱了起来网页,其中有一个表单创建两个相关模型(组织&员工),并使用一个会话中的第三个(Employee_Role)
  • 存储这些信息并在稍后使用该会话。

一般情景:

联系注册等填充: 的组织名称 和用户名&密码&电子邮件(用于管理员工)

如果值是有效的,那么系统会创建具有auto_generated organization_id的“组织”。

然后,系统会创建“雇员”(这将需要的organization_ID这个用户分配管理员“Employee_Role”)

然后,系统会保持在会议的下列信息:(的organization_ID,EMPLOYEE_ID,ROLE_ID,时间戳)并把用户带到管理主页。

请注意,我将模型保留在通用文件夹和控制器的前端,因此应该是视图。

我感谢您的帮助,

回答

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() ?> 
+0

帮助很大,谢谢 –