Magento2 | PWA | GraphQL

How to Set and Get Data Using Data Persistor - Magento2


Data Persistor in Magento 2 is a class that stores data of the user’s current session. It is used to store temporary data, meaning that the data does not need to be stored in the database. You can get, set and clear data from the user session using Data Persistor.

So let’s find out How to Set, Get and Clear Data Using Data Persistor Dynamically in Magento 2.

  • We can use DataPersistor mostly in the DataProvider class in the UI Component grid.

<?php
/**
 * Copyright ©  All rights reserved.
 * See COPYING.txt for license details.
 */
declare(strict_types=1);
 
namespace Vendor\Module\Model\Entity;
 
use Magento\Framework\App\Request\DataPersistorInterface;
use Magento\Ui\DataProvider\AbstractDataProvider;
 
class DataProvider extends AbstractDataProvider
{
 
    /**
     * @var DataPersistorInterface
     */
    protected $dataPersistor;
 
    /**
     * @var array
     */
    protected $loadedData;
    /**
     * @inheritDoc
     */
    protected $collection;
 
    public function __construct(
        DataPersistorInterface $dataPersistor
    ) {
        $this->dataPersistor = $dataPersistor;
      }
 
    /**
     * @inheritDoc
     */
    public function getData()
    {
        if (isset($this->loadedData)) {
            return $this->loadedData;
        }
        $items = $this->collection->getItems();
        foreach ($items as $model) {
            $this->loadedData[$model->getId()] = $model->getData();
        }
        $data = $this->dataPersistor->get('vendor_module_entity');
         
        if (!empty($data)) {
            $model = $this->collection->getNewEmptyItem();
            $model->setData($data);
            $this->loadedData[$model->getId()] = $model->getData();
            $this->dataPersistor->clear('vendor_module_entity');
        }
         
        return $this->loadedData;
    }
}

  • You can also use DataPersistor in Controller class to Save the Entity.

<?php
/**
 * Copyright ©  All rights reserved.
 * See COPYING.txt for license details.
 */
declare(strict_types=1);
 
namespace Vendor\Module\Controller\Adminhtml\Entity;
 
use Magento\Framework\Exception\LocalizedException;
 
class Save extends \Magento\Backend\App\Action
{
 
    protected $dataPersistor;
 
    /**
     * @param \Magento\Backend\App\Action\Context $context
     * @param \Magento\Framework\App\Request\DataPersistorInterface $dataPersistor
     */
    public function __construct(
        \Magento\Backend\App\Action\Context $context,
        \Magento\Framework\App\Request\DataPersistorInterface $dataPersistor
    ) {
        $this->dataPersistor = $dataPersistor;
        parent::__construct($context);
    }
 
    /**
     * Save action
     *
     * @return \Magento\Framework\Controller\ResultInterface
     */
    public function execute()
    {
        /** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */
        $resultRedirect = $this->resultRedirectFactory->create();
        $data = $this->getRequest()->getPostValue();
        if ($data) {
            $id = $this->getRequest()->getParam('id');
         
            $model = $this->_objectManager->create(\Vendor\Module\Model\Entity::class)->load($id);
            if (!$model->getId() && $id) {
                $this->messageManager->addErrorMessage(__('This Entity no longer exists.'));
                return $resultRedirect->setPath('*/*/');
            }
         
            $model->setData($data);
         
            try {
                $model->save();
                $this->messageManager->addSuccessMessage(__('You saved the Entity.'));
                $this->dataPersistor->clear('vendor_module_entity');
         
                if ($this->getRequest()->getParam('back')) {
                    return $resultRedirect->setPath('*/*/edit', ['id' => $model->getId()]);
                }
                return $resultRedirect->setPath('*/*/');
            } catch (LocalizedException $e) {
                $this->messageManager->addErrorMessage($e->getMessage());
            } catch (\Exception $e) {
                $this->messageManager->addExceptionMessage($e, __('Something went wrong while saving the Entity.'));
            }
         
            $this->dataPersistor->set('vendor_module_entity', $data);
            return $resultRedirect->setPath('*/*/edit', ['id' => $this->getRequest()->getParam('id')]);
        }
        return $resultRedirect->setPath('*/*/');
    }
}
Tag : Magento2
0 Comments On "How to Set and Get Data Using Data Persistor - Magento2"

Back To Top