2016-11-22 53 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

幫助很大,謝謝 –