From 483fbc8499a5735a79cbe42a47419b90b682c129 Mon Sep 17 00:00:00 2001 From: Robbie Averill Date: Fri, 17 May 2019 15:51:11 +1200 Subject: [PATCH] FIX Preview email link now handles cases where it's loaded in the browser, requested via AJAX and used in a trait or a page context --- code/Model/Recipient/EmailRecipient.php | 21 ++++++++++++-------- tests/Model/Recipient/EmailRecipientTest.php | 2 +- 2 files changed, 14 insertions(+), 9 deletions(-) diff --git a/code/Model/Recipient/EmailRecipient.php b/code/Model/Recipient/EmailRecipient.php index 6f33922..ff3487d 100644 --- a/code/Model/Recipient/EmailRecipient.php +++ b/code/Model/Recipient/EmailRecipient.php @@ -229,16 +229,21 @@ class EmailRecipient extends DataObject // Only show the preview link if the recipient has been saved. if (!empty($this->EmailTemplate)) { - $pageEditController = singleton(CMSPageEditController::class); - $pageEditController - ->getRequest() - ->setSession(Controller::curr()->getRequest()->getSession()); + $request = Controller::curr()->getRequest(); + $pageEditController = singleton(CMSPageEditController::class); + $pageEditController->getRequest()->setSession($request->getSession()); + + $currentUrl = $request->getURL(); // If used in a regular page context, will have "/edit" on the end, if used in a trait context - // it won't. Strip that off in case. - $currentUrl = Controller::curr()->getRequest()->getURL(); - if (substr($currentUrl, -5) === '/edit') { - $currentUrl = substr($currentUrl, 0, strlen($currentUrl) - 5); + // it won't. Strip that off in case. It may also have "ItemEditForm" on the end instead if this is + // an AJAX request, e.g. saving a GridFieldDetailForm + $remove = ['/edit', '/ItemEditForm']; + foreach ($remove as $badSuffix) { + $badSuffixLength = strlen($badSuffix); + if (substr($currentUrl, -$badSuffixLength) === $badSuffix) { + $currentUrl = substr($currentUrl, 0, -$badSuffixLength); + } } $previewUrl = Controller::join_links($currentUrl, 'preview'); diff --git a/tests/Model/Recipient/EmailRecipientTest.php b/tests/Model/Recipient/EmailRecipientTest.php index 742e1e6..30cf0cc 100644 --- a/tests/Model/Recipient/EmailRecipientTest.php +++ b/tests/Model/Recipient/EmailRecipientTest.php @@ -29,7 +29,7 @@ class EmailRecipientTest extends SapphireTest } /** - * @expectedException SilverStripe\ORM\ValidationException + * @expectedException \SilverStripe\ORM\ValidationException * @expectedExceptionMessage "Send email to" address or field is required */ public function testEmptyRecipientFailsValidation()