How to Save Form Data to the Custom Table in Magento 2
Today’s tutorial explains how you can save form data to the custom table in Magento 2.
When you fill out details in a form and click on a Submit button, the data has to be stored in a table. To do that, you will need to create Submit.php file.
For instance, if you want to collect name, email addresses and telephone number of customers for sending newsletters, the data should be stored in a database. If the data is not stored in the database, we simply cannot access and send newsletters.
Learn the programmatic method as shown below:
Method to Save Form Data to the Custom Table in Magento 2:
Create a file app\code\Extension\Controller\Index\Submit.php
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 |
<?php namespace Meetanshi\Extension\Controller\Index; use Magento\Framework\App\Action\Context; use Magento\Framework\View\Result\PageFactory; use Meetanshi\Extension\Model\ExtensionFactory; use Magento\Framework\Controller\ResultFactory; use Magento\Framework\App\Action\Action; class Submit extends Action { protected $resultPageFactory; protected $extensionFactory; public function __construct( Context $context, PageFactory $resultPageFactory, ExtensionFactory $extensionFactory ) { $this->resultPageFactory = $resultPageFactory; $this->extensionFactory = $extensionFactory; parent::__construct($context); } public function execute() { try { $data = (array)$this->getRequest()->getPost(); if ($data) { $model = $this->extensionFactory->create(); $model->setData($data)->save(); $this->messageManager->addSuccessMessage(__("Data Saved Successfully.")); } } catch (\Exception $e) { $this->messageManager->addErrorMessage($e, __("We can\'t submit your request, Please try again.")); } $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT); $resultRedirect->setUrl($this->_redirect->getRefererUrl()); return $resultRedirect; } } |
Implement the code and you will be able to save data in the database. As we have written the message “Data Saved Successfully” to display while submitting the data, the same message will appear when the data is being saved.
That’s it. Also to prevent yourself from multiple form submission and storing same data of same user, once clicked on submit button disable submit button on form submission.
If you have queries like getting “Invalid Form Key” or any other queries regarding this blog, feel free to ask in the Comment section below.
I will try my level best to solve your problem.
Do consider sharing this blog post with the beginners who are willing to learn Magento extension development.
Thank you.
Jignesh Parmar
An expert in his field, Jignesh is the team leader at Meetanshi and a certified Magento developer. His passion for Magento has inspired others in the team too. Apart from work, he is a cricket lover.
24 Comments
HI,
I didn,t get successful message on save.
but data i ssaved in database.
Hi Kirandeep I Would Like to ask you if Any other error/success messages are working or not ?
If yes than try to add this on your custom form layout file :
If still the issue continues please do let us know.
it is redirecting me t homepage and no form is shown . How to get rid of it
Hello Hitali,
Please clear the cache and check.
Thank You
Hi Your code uses object manager right?
I created the table in db_schema.xml file. when I click on submit, I’m getting this error
1 exception(s):
Exception #0 (ReflectionException): Class DckapCrudControllerIndexSubmitInterceptor does not exist
Exception #0 (ReflectionException): Class DckapCrudControllerIndexSubmitInterceptor does not exist
kindly help
Hello Mohmad,
No, the above solution does not use object manager.
Please clear the cache and check.
Thank You
hello! I am getting this error after submitting the form.
Warning: Illegal offset type in isset or empty
already run all the commands but this error is displaying
Hello Syed,
The Parameters that are passing are different from the parameters that are being used.
Thank You
use Meetanshi\Extension\Model\ExtensionFactory; from where i’ll get this dependency???
Hello Pravin,
The factory class gets generated dynamically.
Thank You
Class Meetanshi\Extension\Model\ExtensionFactory does not exist
Class ITG\HelloWorld\Controller\FormHandel\Post\Interceptor generation erro
r: The requested class did not generate properly, because the ‘generated’ d
irectory permission is read-only. If — after running the ‘bin/magento set
up:di:compile’ CLI command when the ‘generated’ directory permission is set
to write — the requested class did not generate properly, then you must
add the generated class object to the signature of the related construct me
thod, only.
Hello Alaa,
There’s a mistake in class name and the extension name is different from the used class!
Thank You
hello i got error in this
{“0″:”Class Signup\Form\Controller\Index\Submit\Interceptor does not exist”,”1
Hello Sagar,
There’s an error that shows the di:compile command missing.
Thank You
Hi, I did all the steps you have mentioned but getting errors like “INVALID FORM KEY, Please refresh the page” also values are not inserted in the table. Please help me to solve this issue.
Hello Maheshwari,
Please follow the below blog to add form key in your form:
https://meetanshi.com/blog/add-form-key-in-magento-2/
Thank You
1 exception(s):
Exception #0 (ReflectionException): Class Meetanshi\Extension\Controller\Index\Submit\Interceptor does not exist
still, I am facing the same issue after run php bin/magento cache:flush
Hello talha,
It’s an issue of generator.
Please run the below command:
php bin/magento setup:di:compile
Thank You.
I had created one table in installschema for storing the question from the admin panel and one table to save the data from the getquote form. Now I want to know how this code is telling that save the data in a particular table.
Hello Kirti,
That depends on the model factory you are using.
Please follow this blog for required solution: https://meetanshi.com/blog/create-model-file-to-perform-crud-operation-in-magento-2/
Thank You.
I follow all the steps.
my form is being display on frontend
table is also got created but data is not being insert in table.
I’m unable to solve this issue please help me to insert the data into the database
Hello Feeroz,
Just print the log in the controller file and check if the data is fetched or not.
Refer https://meetanshi.com/blog/print-log-in-magento-2/
Thank You.
{“0″:”Class Meetanshi\Extension\Controller\Index\Submit\Interceptor does not exist”,”1″:”
Hello Shahid,
Please run this command for caching:
php bin/magento cache:flush
Thank you