Skip to content

Commit

Permalink
Use asModelFailure and asModelSuccess
Browse files Browse the repository at this point in the history
  • Loading branch information
bencroker authored Feb 9, 2024
1 parent 51db507 commit 69b83a3
Showing 1 changed file with 12 additions and 35 deletions.
47 changes: 12 additions & 35 deletions src/controllers/SaveController.php
Original file line number Diff line number Diff line change
Expand Up @@ -161,56 +161,33 @@ private function _returnSuccess(Entry $entry, $isSpam = false): Response
]));
}

if (Craft::$app->getRequest()->getAcceptsJson()) {
return $this->asJson([
'success' => true,
'id' => $entry->id,
'title' => $entry->title,
'authorUsername' => $entry->getAuthor()->username,
'dateCreated' => DateTimeHelper::toIso8601($entry->dateCreated),
'dateUpdated' => DateTimeHelper::toIso8601($entry->dateUpdated),
'postDate' => $entry->postDate ? DateTimeHelper::toIso8601($entry->postDate) : null,
'url' => $entry->getUrl(),
]);
}

$this->setSuccessFlash(Craft::t('guest-entries', 'Entry saved.'));

return $this->redirectToPostedUrl($entry);
return $this->asModelSuccess(
$entry,
Craft::t('guest-entries', 'Entry saved.'),
$settings->entryVariable,
);
}

/**
* Returns an 'error' response.
*
* @param Settings $settings
* @param Entry $entry
* @return Response|null
* @return Response
*/
private function _returnError(Settings $settings, Entry $entry)
private function _returnError(Settings $settings, Entry $entry): Response
{
if ($this->hasEventHandlers(self::EVENT_AFTER_ERROR)) {
$this->trigger(self::EVENT_AFTER_ERROR, new SaveEvent([
'entry' => $entry,
]));
}

if (Craft::$app->getRequest()->getAcceptsJson()) {
return $this->asJson([
'success' => false,
'errors' => $entry->getErrors(),
]);
}

$this->setFailFlash(Craft::t('guest-entries', 'Couldn’t save entry.'));

// Send the entry back to the template
/** @var UrlManager $urlManager */
$urlManager = Craft::$app->getUrlManager();
$urlManager->setRouteParams([
'variables' => [$settings->entryVariable => $entry],
]);

return null;
return $this->asModelFailure(
$entry,
Craft::t('guest-entries', 'Couldn’t save entry.'),
$settings->entryVariable,
);
}

/**
Expand Down

0 comments on commit 69b83a3

Please sign in to comment.