2

I have created a custom module for Distributor registration its having a custom form with some extra fields for registration. Distributor registration is working fine but i am not able to retain the form filed value in case there if there is server side validation error.

I have tried to followed customer registration module and form and found that Magento keeps the value in session like this.

in CreatePost.php controller

$this->session->setCustomerFormData($this->getRequest()->getPostValue());

and retaining the form value by bellow line of code in form.

<?php echo $block->escapeHtml($block->getFormData()->getCity()) ?>

Is there any other way i can use to keep the form filled in case of validation error ?

  • Please add code which you have used in controller file and block file. – John Feb 9 '17 at 13:14
1

If you check Customer module in Magento 2, you will find that it is using $block->getFormData() function to get data.
Now when you go to Customer\Block\Form\Register block, you will find getFormData function,

public function getFormData()
{
    $data = $this->getData('form_data');
    if ($data === null) {
        $formData = $this->_customerSession->getCustomerFormData(true);
        $data = new \Magento\Framework\DataObject();
        if ($formData) {
            $data->addData($formData);
            $data->setCustomerData(1);
        }
        if (isset($data['region_id'])) {
            $data['region_id'] = (int)$data['region_id'];
        }
        $this->setData('form_data', $data);
    }
    return $data;
}

This function gets data from session you set in your controller with code

$this->_customerSession->setCustomerFormData($this->getRequest()->getPostValue());

and set it in a variable form_data which is used as $block->getFormData in phtml file. You also need to create the same function in your block to get data.

  • i did the same but somehow its not working. I have the value in the session but still getFormData() is showing empty error – Abhijeet kumar sharma Feb 9 '17 at 2:40
  • Can you please add your controller and block file code to you question? – Jaimin Sutariya Feb 9 '17 at 2:41
  • Some how session data in not coming in block. When i am writing this $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $session = $objectManager->create('Magento\Customer\Model\Session'); then form data is working.. – Abhijeet kumar sharma Feb 9 '17 at 3:02
  • Are you saving data in customer session? Can put your code for adding data to customer session – Jaimin Sutariya Feb 9 '17 at 3:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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