Magento 2.3 - Controller plugin redirect back to form loses form values
-
15-04-2021 - |
Question
I have a plugin running on the aroundExecute of the Magento\Customer\Controller\Account\CreatePost controller.
use Magento\Framework\Controller\Result\RedirectFactory;
use Magento\Framework\UrlFactory;
use Magento\Framework\Message\ManagerInterface;
public function __construct(
UrlFactory $urlFactory,
RedirectFactory $redirectFactory,
ManagerInterface $messageManager
)
{
$this->urlModel = $urlFactory->create();
$this->resultRedirectFactory = $redirectFactory;
$this->messageManager = $messageManager;
}
public function aroundExecute(
\Magento\Customer\Controller\Account\CreatePost $subject,
\Closure $proceed
)
{
$this->messageManager->addErrorMessage(
'Error testing'
);
$defaultUrl = $this->urlModel->getUrl('*/*/create', ['_secure' => true]);
$resultRedirect = $this->resultRedirectFactory->create();
return $resultRedirect->setUrl($defaultUrl);
}
This works fine, but all form values on the registration form are lost on redirect back. Any idea how I can pass them back to the original form and have them repopulate the form fields? Thanks
Solution
You can set it in session as the core controller does it.
Take a look at the Magento\Customer\Controller\Account\CreatePost::execute
in the catch
section.
$this->session->setCustomerFormData($this->getRequest()->getPostValue());
But you also need to add an instance of Magento\Customer\Model\Session
as a dependency to your class.
use Magento\Framework\Controller\Result\RedirectFactory;
use Magento\Framework\UrlFactory;
use Magento\Framework\Message\ManagerInterface;
private $session;
public function __construct(
UrlFactory $urlFactory,
RedirectFactory $redirectFactory,
ManagerInterface $messageManager,
\Magento\Customer\Model\Session $session
)
{
$this->urlModel = $urlFactory->create();
$this->resultRedirectFactory = $redirectFactory;
$this->messageManager = $messageManager;
$this->session = $session;
}
public function aroundExecute(
\Magento\Customer\Controller\Account\CreatePost $subject,
\Closure $proceed
)
{
$this->messageManager->addErrorMessage(
'Error testing'
);
$this->session->setCustomerFormData($subject->getRequest()->getPostValue());
$defaultUrl = $this->urlModel->getUrl('*/*/create', ['_secure' => true]);
$resultRedirect = $this->resultRedirectFactory->create();
return $resultRedirect->setUrl($defaultUrl);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange