/** * Creates a new StudentPhone model. * If creation is successful, the browser will be redirected to the 'view' page. * @return mixed */ public function actionCreate($studentId) { $student = Student::findOne($studentId); if (!user()->can('updateStudent', ['student' => $student])) { setError('Access denied.'); return $this->redirect(['/student/view', 'id' => $studentId], 403); } $model = new StudentPhone(); if ($model->load(Yii::$app->request->post()) && $model->save()) { return $this->redirect(['view', 'id' => $model->id]); } else { return $this->render('create', ['student' => $student, 'model' => $model]); } }
/** * Creates a new Student model. * If creation is successful, the browser will be redirected to the either * the index or the create page to add another. * @return mixed */ public function actionCreate() { $transaction = Yii::$app->db->beginTransaction(); // Get the user's school and the current date. $schoolId = Yii::$app->user->schoolId; $today = date('Y-m-d'); $student = new Student(); $student->contract_school_id = $schoolId; $student->start_date = $today; if ($student->load(Yii::$app->request->post()) && $student->save()) { // Affiliate the new student with the same school as the user $role = Role::find()->where(['like', 'name', 'student'])->one(); $affiliation = new Affiliation(); if ($affiliation->load(Yii::$app->request->post())) { $affiliation->student_id = $student->id; $affiliation->school_id = $schoolId; $affiliation->role_id = $role->id; $affiliation->date = $today; $affiliation->save(); } /* Get the phone # that was posted along with the new student, * and assign it to the student via the newly-created ID. */ $phone = new StudentPhone(); if ($phone->load(Yii::$app->request->post())) { $phone->student_id = $student->id; $phone->save(); } if ($affiliation->isSaved && $phone->isSaved) { $transaction->commit(); $url = Html::a($student->name, ['update', 'id' => $student->id]); Yii::$app->session->setFlash('success', 'Student added: ' . $url); if (Yii::$app->request->post('then-add') !== null) { return $this->redirect(['create']); } elseif (Yii::$app->request->post('then-edit') !== null) { return $this->redirect(['update', 'id' => $student->id]); } else { return $this->redirect(['index']); } } else { $transaction->rollBack(); $msg = 'Unable to create student: '; //!!! find a better way to extract the model errors $msg .= serialize($affiliation->errors); $msg .= serialize($phone->errors); Yii::$app->session->setFlash('error', $msg); } } return $this->render('create', ['model' => $student]); }