How to Create Custom Form in Magento 2
The shopping experience in an online store is a huge factor and store owners do not leave any stone unturned in employing strategies to collect maximum customer data for improving their store experience.
Success in today’s competitive E-commerce market depends on calculative decisions based on data and analysis. Also, as a customer, allowing businesses to process your data benefits you in ways like better service, personalized and quick recommendations, etc.
One of the ways to collect customer data is through forms. As default Magento 2 does not offer sufficient forms and its fields, I have posted a programmatic method to create custom form in Magento 2.
With the below solution, you can create a form in Magento 2 with fields like text, numbers, date, etc. Not only this, but you can set validation for each field to ensure correct data collection from the Magento 2 frontend customers.
You can create Magento 2 custom forms like feedback form, surveys, contact form, registration form, donation form, audit form, etc. It depends on the type and requirements of your business.
Method to create custom form in Magento 2:
- Update code in file Form.php at app\code\Meetanshi\Extension\Block
12345678910111213141516171819<?phpnamespace Meetanshi\Extension\Block;use Magento\Framework\View\Element\Template;use Magento\Backend\Block\Template\Context;class Form extends Template{public function __construct(Context $context, array $data = []){parent::__construct($context, $data);}public function getFormAction(){return $this->getUrl('extension/index/submit', ['_secure' => true]);}} - Update code in file form.phtml at app\code\Meetanshi\Extension\view\frontend\templates
123456789101112131415161718192021222324252627282930313233343536373839404142434445<div class="row"><div class="col-md-8"><form name="addData" method="post" id="addData" class="form"action="<?php echo $this->getFormAction(); ?>"data-hasrequired="<?= $block->escapeHtmlAttr(__('* Required Fields')) ?>"data-mage-init='{"validation":{}}'><fieldset class="fieldset"><legend class="legend"><span><?= $block->escapeHtmlAttr(__('Fill Detail')) ?></span></legend><fieldset class="fieldset row"><div class="fields col-md-6"><div class="field name required"><label class="label" for="title"><span><?= $block->escapeHtmlAttr(__('Name')) ?></span></label><div class="control"><input name="name" id="name" title="Name" value="" class="input-text" type="text"data-validate="{required:true, 'validate-alphanum-with-spaces':true}"></div></div><div class="field name required"><label class="label" for="title"><span><?= $block->escapeHtmlAttr(__('Email')) ?></span></label><div class="control"><input name="email" id="email" title="Email" value="" class="input-text" type="text"data-validate="{required:true, 'validate-email':true}"></div></div><div class="field name required"><label class="label" for="title"><span><?= $block->escapeHtmlAttr(__('Telephone')) ?></span></label><div class="control"><input name="telephone" id="telephone" title="Telephone" value="" class="input-text"type="text" data-validate="{required:true}"></div></div></div></fieldset></fieldset><div class="actions-toolbar"><div class="primary"><button type="submit" class="action submit primary" title="Save"><span><?= $block->escapeHtmlAttr(__('Save')) ?></span></button></div></div></form></div></div>
We have created getFormAction() in block file that will be used in the template file.
Additionally, if the form is long enough, you can add checkout-like progress bar to it and make it easy for the customers to fill up.
This is how your custom form in Magento 2 will appear frontend.Create new database table in Magento 2 to store and retrieve the data. Not only that, but you can also perform various operations such as insert, update and delete on the table data.
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 in Magento 2.
Now that you know the solution to create Magento 2 form and collect customer data, you are all set to have a database that is going to be the cornerstone of your marketing strategy! You may also love to read How to Add Validation For Custom Password Field in Magento 2.
Any doubts with the topic? Do mention them in the Comments section below. I’d be happy to help.
Also, please share the solution with Magento 2 developers via social media.
Thank you.
Previous
How to Create Block and Template in Magento 2
Manage department-wise contact inquiries in your online store with ease using Magento 2 Custom Contact Form extension
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.
23 Comments
I do love the way you have presented this specific problem and it does present us some fodder for consideration. On the other hand, because of what I have observed, I basically trust as the actual commentary pack on that people today remain on issue and don’t embark on a soap box involving the news of the day. Anyway, thank you for this exceptional point and although I do not agree with the idea in totality, I regard your viewpoint.
Thank You So much for such an appreciative feedback!
i follow the same steps but fields not display on frontend ?
my url=priya.magento.com/hef/index/index
Hello Priya,
Please follow the above steps properly as it is properly working from our end.
Thank You
Hi! Can you please share with us how to access the form data using controller (using getFormAction()) and also how to save that data in database?
Hello,
Please refer https://meetanshi.com/blog/magento-2-create-table/ for the required solution.
Thanks.
Hello Olegsandr,
I would recommend you to check the next step. You will understand all the things.
Thank you.
Hello,
unfortunatly this seems to not working with me
I got this “/catalogsearch/result/?q=extension+index+index&amnoroute” when trying to access.
🙁
Hello Frank,
The issue is caused due to the advanced search that is implemented in the store.
Please clear cache and check again.
Thank you.
Hi ,
I followed the same way as you told in the article but it show 404 error when I search with “http://localhost/magento2/extension/index/index” this url
Hello Varsha,
Please clear cache and check again.
Thank you.
Hi,
How to access this form in browser? In URL what to give?
Thanks in Advance….
Hello,
You can access using this URL – website_url/extension/index/index
Thanks.
Its not working
Hello,
Can you mention the error you are getting?
Thank you.
How to access this form in browser? URL?
Hello,
You can access using this URL – website_url/extension/index/index
Thanks.
Hi, I am a non php programmer but have done little things in Magento. Just wanted to know where this data will be collected. Will it be send by email like formmail or will be stored in Database to further view the same in the Admin Panel. From the code I can see the database is not setup, so I assume it will be sent by email? Am I correct?
Hello Jay,
To save this data, you need to create a controller.
Thanks.
Hey,
Can you please suggest how to get sign up form data in the custom form as prefilled in Magento 2.
Thanks in advance!
Hello Rashi,
You can do this for login customer in Block file from customer session.
Directly get data from the block file in phtml and input field like value=”$var”
Thanks.
Hello,
after i send the form goes to page “extension/index/submit” but give me an error 404.
Can you help me?
Hello,
You need to create app/code/Vendor/Extension/Controller/Index/submit.php file as shown in step 5.
Thank you.