1

How to save custom frontend form to database in Magento2.2.5?

Any help would be appreciated

4
  • 1
    You have created a frontend form or need the whole code including form creation? Feb 21, 2019 at 7:57
  • I have created my form but I am not able to submit my values to db.
    – Amy
    Feb 21, 2019 at 7:59
  • see my answer i have used this already in my form and its working for me. Feb 21, 2019 at 8:03
  • Okay i will check it.. and let you know
    – Amy
    Feb 21, 2019 at 8:03

1 Answer 1

0

You can save the form data using the controller :

namespace VendorName\ModuleName\Controller\Customer;
use Magento\Framework\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;

class Save extends \Magento\Framework\App\Action\Action
{
    protected $resultPageFactory;

    protected $session;

    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        PageFactory $resultPageFactory
        )
    {
        parent::__construct($context);
        $this->resultPageFactory = $resultPageFactory;
    }
    public function execute()
    {
        $resultRedirect = $this->resultRedirectFactory->create();

            //$resultPage = $this->resultPageFactory->create();
            //$resultPage->getConfig()->getTitle()->set(__('Helpdesk'));
            //return $resultPage;
            $data = $this->getRequest()->getPostValue();

            $model = $this->_objectManager->create('VendorName\ModuleName\Model\ModelName');
            $model->setData($data);
            try {
                $model->save();
                $this->messageManager->addSuccess(__('The Data has been saved.'));
                return $resultRedirect->setPath('*/*/');
            } catch (\Magento\Framework\Exception\LocalizedException $e) {
                $this->messageManager->addError($e->getMessage());
            } catch (\RuntimeException $e) {
                $this->messageManager->addError($e->getMessage());
            } catch (\Exception $e) {
                $this->messageManager->addException($e, __('Something went wrong while saving the Data.'));
            }
        }
}
2
  • can you share me your full code.
    – Amy
    Feb 21, 2019 at 9:16
  • The data's are inserted successfully..thanks
    – Amy
    Feb 21, 2019 at 10:55

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.