/** * Saves an event. * * @param Events_EventModel $event * @throws Exception * @return bool */ public function saveEvent(Events_EventModel $event) { $isNewEvent = !$event->id; // Event data if (!$isNewEvent) { $eventRecord = Events_EventRecord::model()->findById($event->id); if (!$eventRecord) { throw new Exception(Craft::t('No event exists with the ID “{id}”', array('id' => $event->id))); } } else { $eventRecord = new Events_EventRecord(); } $eventRecord->calendarId = $event->calendarId; $eventRecord->startDate = $event->startDate; $eventRecord->endDate = $event->endDate; $eventRecord->validate(); $event->addErrors($eventRecord->getErrors()); if (!$event->hasErrors()) { $transaction = craft()->db->getCurrentTransaction() === null ? craft()->db->beginTransaction() : null; try { // Fire an 'onBeforeSaveEvent' event $this->onBeforeSaveEvent(new Event($this, array('event' => $event, 'isNewEvent' => $isNewEvent))); if (craft()->elements->saveElement($event)) { // Now that we have an element ID, save it on the other stuff if ($isNewEvent) { $eventRecord->id = $event->id; } $eventRecord->save(false); // Fire an 'onSaveEvent' event $this->onSaveEvent(new Event($this, array('event' => $event, 'isNewEvent' => $isNewEvent))); if ($transaction !== null) { $transaction->commit(); } return true; } } catch (\Exception $e) { if ($transaction !== null) { $transaction->rollback(); } throw $e; } } return false; }
/** * Populates an element model based on a query result. * * @param array $row * @return array */ public function populateElementModel($row) { return Events_EventModel::populateModel($row); }
/** * Saves an event. */ public function actionSaveEvent() { $this->requirePostRequest(); $eventId = craft()->request->getPost('eventId'); if ($eventId) { $event = craft()->events->getEventById($eventId); if (!$event) { throw new Exception(Craft::t('No event exists with the ID “{id}”', array('id' => $eventId))); } } else { $event = new Events_EventModel(); } // Set the event attributes, defaulting to the existing values for whatever is missing from the post data $event->calendarId = craft()->request->getPost('calendarId', $event->calendarId); $event->startDate = ($startDate = craft()->request->getPost('startDate')) ? DateTime::createFromString($startDate, craft()->timezone) : null; $event->endDate = ($endDate = craft()->request->getPost('endDate')) ? DateTime::createFromString($endDate, craft()->timezone) : null; $event->getContent()->title = craft()->request->getPost('title', $event->title); $event->setContentFromPost('fields'); if (craft()->events->saveEvent($event)) { craft()->userSession->setNotice(Craft::t('Event saved.')); $this->redirectToPostedUrl($event); } else { craft()->userSession->setError(Craft::t('Couldn’t save event.')); // Send the event back to the template craft()->urlManager->setRouteVariables(array('event' => $event)); } }