DEV Community

Tschallacka
Tschallacka

Posted on

How to persist data between requests for form validation in Magento 2

The DataPersistorInterface is used to persist data temporarily for later use, such as during a redirect.

It is often used in controllers to store form data in the session so that it can be used to pre-populate a form if there is an error in form submission.

public function execute()
{
    $post = $this->getRequest()->getPostValue();
    $resultRedirect = $this->resultRedirectFactory->create();
    if ($post) {
        $model = $this->contactFactory->create($post);
        try {
            $this->contactRepository->save($model);
            $this->messageManager->addSuccessMessage(__('Your inquiry was submitted and will be responded to as soon as possible. Thank you for contacting us.'));
            $this->dataPersistor->clear('contact_us');
            return $resultRedirect->setPath('contact/index');
        } catch (LocalizedException $e) {
            $this->messageManager->addErrorMessage($e->getMessage());
        } catch (\Exception $e) {
            $this->messageManager->addExceptionMessage($e, __('An error occurred while processing your form. Please try again later.'));
        }

        $this->dataPersistor->set('contact_us', $post);
        return $resultRedirect->setPath('contact/index');
    }
    return $resultRedirect->setPath('contact/index');
}
Enter fullscreen mode Exit fullscreen mode

To use it simple include the Magento\Framework\App\Request\DataPersistorInterface in your __construct()

use Magento\Framework\App\Request\DataPersistorInterface;

class YourClass {

  protected DataPersistorInterface $dataPersistor;

  public function __construct(
     DataPersistorInterface $dataPersistor
  ) {
      $this->dataPersistor = $dataPersistor;
  }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)