In this blog, we’ll learn what is data persistor and how to use it. When we fill out a form and something goes wrong in it, then the whole form is reloaded and the data gets erased. It’s very difficult to enter all data one by one. Data persistor will solve this problem. It’s just a class that stores data on the current user session. You can set, get, and clear data from the session.
Step 1- Add layout file with argument( form_index_index.xml)
Create layout file in app/codeBluethink/Customform/view/frontend/layout.
In your layout file, you need to add argument as shown below:
1 2 3 4 5 6 7 8 9 10 |
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd"> <body> <referenceContainer name="content"> <block class="Magento\Framework\View\Element\Template" name="custom_form" template="Bluethink_Customform::insert.phtml"> <argument name="view_model" xsi:type="object">Bluethink\Customform\ViewModel\UserDataProvider </argument> </block> </referenceContainer> </body> </page> |
Step2 – Now we need to get data of user.
We need entered data of user to display on text field.
Create UserDataProvider.php in app/code/Bluethink/Customform/ViewModel folder.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
<?php namespace Bluethink\Customform\ViewModel; use Bluethink\Customform\Helper\Data; use Magento\Framework\View\Element\Block\ArgumentInterface; /** * Provides the user data to fill the form. */ class UserDataProvider implements ArgumentInterface { /** * @var Data */ private $helper; /** * UserDataProvider constructor. * @param Data $helper */ public function __construct( Data $helper ) { $this->helper = $helper; } /** * Get user name * * @return string */ public function getUserName() { return $this->helper->getPostValue('name'); } /** * Get user email * * @return string */ public function getUserEmail() { return $this->helper->getPostValue('email'); } /** * Get user experience * * @return string */ public function getUserExperience() { return $this->helper->getPostValue('experience'); } /** * Get user comment * * @return string */ public function getUserPost() { return $this->helper->getPostValue('post'); } } |
Now we have customer data 🙂
Step 3- We create function required by ViewModel UserDataProvider
Create helper file Data.php in app/code/Bluethink/Customform/Helper folder.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
<?php namespace Bluethink\Customform\Helper; use Magento\Framework\App\ObjectManager; use Magento\Framework\App\Request\DataPersistorInterface; class Data extends \Magento\Framework\App\Helper\AbstractHelper { /** * @var DataPersistorInterface */ private $dataPersistor; /** * @var array */ private $postData = null; /** * @param \Magento\Framework\App\Helper\Context $context */ public function __construct( \Magento\Framework\App\Helper\Context $context ) { parent::__construct($context); } /** * Get value from POST by key * * @param string $key * @return string */ public function getPostValue($key) { if (null === $this->postData) { $this->postData = (array) $this->getDataPersistor()->get('apply_here'); $this->getDataPersistor()->clear('apply_here'); } if (isset($this->postData[$key])) { return (string) $this->postData[$key]; } return ''; } /** * Get Data Persistor * * @return DataPersistorInterface */ private function getDataPersistor() { if ($this->dataPersistor === null) { $this->dataPersistor = ObjectManager::getInstance() ->get(DataPersistorInterface::class); } return $this->dataPersistor; } } |
Step 4- Let’s Call ViewModel on the Form
Create save.php in Controller/Index folder.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
<?php $viewModel = $block->getViewModel(); ?> <form id="my-form" action="<?= $block->escapeUrl($block->getUrl('form/index/save')) ?>" method="post" data-mage-init='{"validation": {}}'> <label for="name">Name</label> <input type="text" class="input-text required" data-msg-required="enter a valid data" name="name" id="name" value="<?= $block->escapeHtmlAttr($viewModel->getUserName()) ?>"> <label for="email">Email</label> <input type="email" data-validate='{"required":true}' name="email" id="class" value="<?= $block->escapeHtmlAttr($viewModel->getUserEmail()) ?>"> <label for="experience">Experience</label> <input type="text" class="input-text" name="experience" id="mark" value="<?= $block->escapeHtmlAttr($viewModel->getUserExperience()) ?>"> <label for="post">Post</label> <input type="text" class="input-text required" name="post" id="gender" value="<?= $block->escapeHtmlAttr($viewModel->getUserPost()) ?>"><br><br> <input type="submit" value="Save" class="input-text " name="submit"> </form> <script type="text/x-magento-init"> { "#my-form": { "validation": {} } } </script> |
Step 5 – We need to call data persistor on the controller
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 |
<?php namespace Bluethink\Customform\Controller\Index; use \Magento\Framework\App\Action\Action; use Magento\Framework\App\Action\Context; use Magento\Framework\Exception\LocalizedException; use Magento\Framework\App\Request\DataPersistorInterface; class Save extends Action { /** * @var DataPersistorInterface */ private $dataPersistor; /** * @var Context */ private $context; /** * @var UploaderFactory */ protected $uploaderFactory; /** * @var AdapterFactory */ protected $adapterFactory; /** * @var Filesystem */ protected $filesystem; /** * @param Context $context */ public function __construct( Context $context, DataPersistorInterface $dataPersistor ) { $this->dataPersistor = $dataPersistor; $this->context = $context; parent::__construct($context); } /** * Prints the information * @return Page */ public function execute() { if (!$this->getRequest()->isPost()) { return $this->resultRedirectFactory->create()->setPath('*/*/'); } try { $data = $this->validatedParams(); $this->messageManager->addSuccessMessage( __('Thanks for submitting your profile. We\'ll respond to you very soon.') ); $this->dataPersistor->clear('apply_here'); } catch (LocalizedException $e) { $this->messageManager->addErrorMessage($e->getMessage()); $this->dataPersistor->set('apply_here', $this->getRequest()->getParams()); } catch (\Exception $e) { $this->logger->critical($e); $this->messageManager->addErrorMessage( __('An error occurred while processing your form. Please try again later.') ); $this->dataPersistor->set('apply_here', $this->getRequest()->getParams()); } return $this->resultRedirectFactory->create()->setPath('form/index'); } /** * Method to validated params. * * @return array * @throws \Exception */ private function validatedParams() { $request = $this->getRequest(); if (trim($request->getParam('name', '')) === '') { throw new LocalizedException(__('Enter the Name and try again.')); } if (\strpos($request->getParam('email', ''), '@') === false) { throw new LocalizedException(__('The email address is invalid. Verify the email address and try again.')); } if (trim($request->getParam('experience', '')) === '') { throw new LocalizedException(__('Select the experience and try again.')); } if (trim($request->getParam('post', '')) === '') { throw new LocalizedException(__('Select the post and try again.')); } if (trim($request->getParam('hideit', '')) !== '') { // phpcs:ignore Magento2.Exceptions.DirectThrow throw new \Exception(); } return $request->getParams(); } } |
Please comment is you have any query
Nice blog
2022-12-22 at 10:27 pm