Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use asModelFailure and asModelSuccess in v4 #85

Merged
merged 3 commits into from
Mar 19, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 12 additions & 36 deletions src/controllers/SaveController.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@
use craft\models\Section;
use craft\web\Controller;
use craft\web\Request;
use craft\web\UrlManager;
use yii\web\BadRequestHttpException;
use yii\web\NotFoundHttpException;
use yii\web\Response;
Expand Down Expand Up @@ -161,56 +160,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.'),
'entry',
);
}

/**
* 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
Loading