protected function applySave()
{
// Load the model
$model = $this->getModel()->savestate(false);
if (!$model->getId()) {
$this->getIDsFromRequest($model, true);
}
$userId = $this->container->platform->getUser()->id;
$id = $model->getId();
$data = $this->input->getData();
if ($model->isLocked($userId)) {
try {
$model->checkIn($userId);
} catch (LockedRecord $e) {
// Redirect to the display task
if ($customURL = $this->input->getBase64('returnurl', '')) {
$customURL = base64_decode($customURL);
}
$eventName = 'onAfterApplySaveError';
$result = $this->triggerEvent($eventName, array(&$data, $id, $e));
$url = !empty($customURL) ? $customURL : 'index.php?option=' . $this->container->componentName . '&view=' . $this->container->inflector->pluralize($this->view) . $this->getItemidURLSuffix();
$this->setRedirect($url, $e->getMessage(), 'error');
return false;
}
}
// Set the layout to form, if it's not set in the URL
if (is_null($this->layout)) {
$this->layout = 'form';
}
// Apply the Form name
$formName = 'form.' . $this->layout;
$this->getModel()->setFormName($formName);
// Save the data
$status = true;
$error = null;
try {
$eventName = 'onBeforeApplySave';
$result = $this->triggerEvent($eventName, array(&$data));
if ($id != 0) {
// Try to check-in the record if it's not a new one
$model->unlock();
}
// Save the data
$model->save($data);
$eventName = 'onAfterApplySave';
$result = $this->triggerEvent($eventName, array(&$data, $model->getId()));
$this->input->set('id', $model->getId());
} catch (\Exception $e) {
$status = false;
$error = $e->getMessage();
$eventName = 'onAfterApplySaveError';
$result = $this->triggerEvent($eventName, array(&$data, $model->getId(), $e));
}
if (!$status) {
// Cache the item data in the session. We may need to reuse them if the save fails.
$itemData = $model->getData();
$sessionKey = $this->viewName . '.savedata';
$this->container->session->set($sessionKey, $itemData, $this->container->componentName);
// Redirect on error
$id = $model->getId();
if ($customURL = $this->input->getBase64('returnurl', '')) {
$customURL = base64_decode($customURL);
}
if (!empty($customURL)) {
$url = $customURL;
} elseif ($id != 0) {
$url = 'index.php?option=' . $this->container->componentName . '&view=' . $this->view . '&task=edit&id=' . $id . $this->getItemidURLSuffix();
} else {
$url = 'index.php?option=' . $this->container->componentName . '&view=' . $this->view . '&task=add' . $this->getItemidURLSuffix();
}
$this->setRedirect($url, $error, 'error');
} else {
$sessionKey = $this->viewName . '.savedata';
$this->container->session->set($sessionKey, null, $this->container->componentName);
}
return $status;
}