protected function afterSave() { /** @var $user User */ $userId = $this->followUpUser ?: Yii::app()->user->id; $user = User::model()->findByPk($userId); if ($this->followUpDue) { if ($note = $this->followUpAppointment) { $note->app_start = date("Y-m-d", strtotime($this->followUpDue)); $note->app_user = $user ? $user->use_id : $note->app_user; $note->calendarID = $user ? $user->use_branch : $note->calendarID; } else { if (!$user) { throw new Exception('User for follow up is not selected'); } $note = new Appointment(); $note->app_type = Appointment::TYPE_VALUATION_FOLLOW_UP; $note->app_start = date("Y-m-d", strtotime($this->followUpDue)); $note->app_user = $user->use_id; $note->calendarID = $user->use_branch; $note->app_subject = $this->property->address->toString(', '); $note->setInstructions([$this->dea_id]); } $existingFollowUps = Appointment::model()->findByAttributes(array("app_user" => $note->app_user, 'app_type' => Appointment::TYPE_VALUATION_FOLLOW_UP), array('order' => 'app_start DESC', 'condition' => 'DATE(app_start) = "' . date("Y-m-d", strtotime($note->app_start)) . '"')); if (!$existingFollowUps) { $note->app_start = date("Y-m-d", strtotime($note->app_start)) . " 09:00:00"; // hardcoded time, not best solution ever $note->app_end = date("Y-m-d", strtotime($note->app_start)) . " 09:30:00"; } else { $note->app_start = $existingFollowUps->app_end; $note->app_end = date("Y-m-d H:i:s", strtotime($note->app_start . " + 30 minutes")); } if ($note->save()) { $this->followUpAppointmentId = $note->app_id; $this->saveAttributes(['followUpAppointmentId']); } else { $this->addError("followUpUppointment", "Could not save follow up appointment"); } $this->followUpAppointment = $note; } parent::afterSave(); }