2

I have below code

app\code\Custom\Module\Controller\MyModule\PostForm.php

namespace Custom\Module\Controller\MyModule;

use Magento\Framework\App\Request\DataPersistorInterface;
use Magento\Framework\App\ObjectManager;
use Magento\Framework\App\Filesystem\DirectoryList;

class PostForm extends \Magento\Framework\App\Action\Action {

    /**
     * @var DataPersistorInterface
     */
    private $dataPersistor;

    /** @var  \Magento\Framework\View\Result\Page */
    protected $resultPageFactory;

    /**
     * @var \Magento\Framework\Translate\Inline\StateInterface
     */
    protected $inlineTranslation;

    /**
     * @var \Magento\Framework\Data\Form\FormKey\Validator
     */
    protected $_formKeyValidator;

    /**     * @param \Magento\Framework\App\Action\Context $context      */
    public function __construct(\Magento\Framework\App\Action\Context $context, \Magento\Framework\View\Result\PageFactory $resultPageFactory, \Magento\Framework\Data\Form\FormKey\Validator $formKeyValidator, \Magento\Framework\Translate\Inline\StateInterface $inlineTranslation) {
        $this->resultPageFactory = $resultPageFactory;
        $this->_formKeyValidator = $formKeyValidator;
        $this->inlineTranslation = $inlineTranslation;
        parent::__construct($context);
    }

    /**
     * Post user post
     *
     * @return void
     * @throws \Exception
     */
    public function execute() {

        $resultPage = $this->resultPageFactory->create();
        $resultRedirect = $this->resultRedirectFactory->create();

        $post = $this->getRequest()->getPostValue();

        if (!$post) {
            $this->_redirect('*/*/');
            return;
        }

        if (!$this->_formKeyValidator->validate($this->getRequest())) {
            return $resultRedirect->setPath('*/*/');
        }

        $this->inlineTranslation->suspend();

        $postObject = new \Magento\Framework\DataObject();
        $postObject->setData($post);

        $error = false;
        $errors = [];
        if (!\Zend_Validate::is(trim($post['title']), 'NotEmpty')) {
            $errors[] = __('Please enter title.');
            $error = true;
        }
        if (!\Zend_Validate::is(trim($post['description']), 'NotEmpty')) {
            $errors[] = __('Please enter description.');
            $error = true;
        }


        if ($error) {
            foreach ($errors as $error) {
                $this->messageManager->addErrorMessage($error);
            }
            $this->getDataPersistor()->set('mymodule_post', $post);
            return $resultRedirect->setPath('module/mymodule/new/');
        }
    }

       /**
     * Get Data Persistor
     *
     * @return DataPersistorInterface
     */
    public function getDataPersistor() {
        if ($this->dataPersistor === null) {
            $this->dataPersistor = ObjectManager::getInstance()
                    ->get(DataPersistorInterface::class);
        }

        return $this->dataPersistor;
    }
}

What is purpose of dataPersistor & when i got error my data are not filled up in Form. I have filled up Title, but Description is blank. So when error message display, it should display my filled up Title.

1 Answer 1

3

Finally solved by referring Magento Core Contact Module

vendor\magento\module-contact\Controller\Index\Post.php

public function execute(){
    $post = $this->getRequest()->getPostValue();
}

Will call vendor\magento\module-contact\Helper\Data.php

/**
 * 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('contact_us');
        $this->getDataPersistor()->clear('contact_us');
    }

    if (isset($this->postData[$key])) {
        return (string) $this->postData[$key];
    }

    return '';
}

Make sure in controller while error set name is same

vendor\magento\module-contact\Controller\Index\Post.php

 $this->getDataPersistor()->set('contact_us', $post);

So in vendor\magento\module-contact\view\frontend\templates\form.phtml

<input name="name" id="name" title="<?php /* @escapeNotVerified */ echo __('Name') ?>" value="<?php echo $block->escapeHtml($this->helper('Magento\Contact\Helper\Data')->getPostValue('name') ?: $this->helper('Magento\Contact\Helper\Data')->getUserName()) ?>" class="input-text" type="text" data-validate="{required:true}"/>

This way it always your post data. Hope it helps to others as well. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.