How To Create Custom Form In Magento 2 – Step By Step Guide

Contact Us

×

Get a Free Consultation

Introduction

Creating custom forms in Magento 2 is a powerful way to gather user input and manage data effectively within your online store. Whether you need a contact form, a survey, or a specialized data entry form, understanding the process of building custom forms can significantly enhance your store’s functionality. In this How To Create Custom Form In Magento 2 – Step By Step Guide, we will walk you through the entire process, from setting up the necessary modules to handling form submissions and managing the stored data.

Magento 2’s modular architecture makes it relatively straightforward to create custom forms that integrate seamlessly with your existing setup. By following this comprehensive guide, you’ll not only learn the technical steps involved but also gain insights into best practices that will ensure your custom forms are secure, user-friendly, and optimized for performance.

Custom forms can play a crucial role in enhancing user experience and driving engagement on your website. Whether you’re a developer looking to expand your Magento 2 skills or a store owner seeking to implement custom functionality, this guide is tailored to help you achieve your goals. Let’s dive into the details of creating a custom form in Magento 2.

Read Also: Creating an Online Store from Scratch with Magento

Step 1: Create the Module Structure

First, let’s create the basic directory structure for our module:

app/code/Folio3/CustomForm

Inside the CustomForm directory, create the following folders

  • etc
  • view/frontend/layout
  • Block
  • view/frontend/templates
  • Controller

Step 2: Declare the Module

To declare the module, we need to create a module.xml file under etc/:

Xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Folio3_CustomForm" setup_version="1.0.0"/>
</config>

Next, register the module in registration.php:

<?php
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Folio3_CustomForm',
    __DIR__
);

Step 3: Create the Form Layout

Now, we’ll define the layout XML to load our custom form. Create a new file customform_index_index.xml under view/frontend/layout/:

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd"> <body> <referenceContainer name="content"> <block class="Folio3\CustomForm\Block\Form" name="folio3.customform.form" template="form.phtml"/> </referenceContainer> </body> </page>

Step 4: Create the Form Block

In the Block/ directory, create a file Form.php:

<?php
namespace Folio3\CustomForm\Block;

use Magento\Framework\View\Element\Template;

class Form extends Template

{
    public function getFormAction()
    {
        return $this->getUrl('customform/index/post');
    }
}

Step 5: Create the Form Template

Now, create the form template form.phtml in view/frontend/templates/:

<form action="<?= $block->getFormAction(); ?>" method="post">
    <div>
        <label for="name">Name</label>
        <input type="text" name="name" id="name" required>
    </div>
    <div>
        <label for="email">Email</label>
        <input type="email" name="email" id="email" required>
    </div>
    <div>
        <button type="submit">Submit</button>
    </div>
</form>

Step 6: Handle Form Submission

Create a controller to handle form submission in Controller/Index/Post.php:

<?php
namespace Folio3\CustomForm\Controller\Index;

use Magento\Framework\App\Action\Action;

use Magento\Framework\App\Action\Context;

use Magento\Framework\Controller\ResultFactory;

class Post extends Action
{
    protected $resultFactory;

    public function __construct(

        Context $context,

        ResultFactory $resultFactory

    ) {

        $this->resultFactory = $resultFactory;

        parent::__construct($context);

    }

    public function execute()

    {

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

        if (!$post) {

            return $this->_redirect('*/*/');

        }

        $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);

        $resultRedirect->setUrl($this->_redirect->getRefererUrl());

        // Handle your form data here

        $this->messageManager->addSuccessMessage('Form submitted successfully.');

        return $resultRedirect;

    }

}

Step 7: Add Routes

Define the route for your form submission in etc/frontend/routes.xml:

 

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">

    <router id="standard">

        <route id="customform" frontName="customform">

            <module name="Folio3_CustomForm" />

        </route>

    </router>

</config>

 

Step 8: Test Your Custom Form

Finally, flush the cache and test your custom form by navigating to the following URL:

yourstore.com/customform/index/index

Conclusion

You should see your custom form displayed on this page, and upon submission, it will handle the data as configured. Depending on your needs, you can extend the functionality to either send an email notification to the admin user or save the form data directly into the database.

For example, if you want to notify the admin when a user submits the form, you can configure Magento 2 to trigger an email with all the form details. This is particularly useful for contact forms or any submission where immediate action is required.

Alternatively, if you prefer to store the data for later processing, you can save the records in the database using Magento 2’s model and resource model system. This approach is ideal for collecting survey responses, user feedback, or any information that you might want to analyze or export at a later time. The flexibility of Magento 2 allows you to choose the method that best suits your business requirements.

By integrating these functionalities, your custom form becomes a powerful tool for gathering and managing user input effectively, enhancing the overall capability of your Magento 2 store.

About Author

Picture of Syed Hassan Raza Rizvi

Syed Hassan Raza Rizvi

Hassan Raza is a seasoned SEO expert with over a decade of industry experience. Proficient in SEO, SEM, and digital marketing, he excels in driving online success for businesses. With a passion for writing about cutting-edge technology, AI trends, and eCommerce platforms such as Magento and BigCommerce, Hassan is a digital marketer by day and a tech enthusiast by night. His expertise and enthusiasm for digital trends make him a valuable asset in navigating the ever-evolving landscape of online marketing.

Table of Contents

Related Blogs

Hire Someone to Build a Shopify Store: Step-by-Step Process Guide
Uncategorized

Hire Someone to Build a Shopify Store: Step-by-Step Process Guide

Many businesses look to use Shopify to launch their ecommerce store. This blog covers hiring an expert to build a Shopify store and the benefits they bring. You’re staring at Shopify’s dashboard, wondering if you should tackle this yourself or bring in professional help.  Here’s the reality: 73% of business owners who attempt DIY e-commerce

Read More
Ecommerce Growth Accelerator vs Traditional Growth Strategies: What Delivers Faster ROI?
Uncategorized

Ecommerce Growth Accelerator vs Traditional Growth Strategies: What Delivers Faster ROI?

Marketing budgets dropped 15% to just 7.7% of revenue in 2024, while customer acquisition costs surged 222% over the past decade.  Enterprise ecommerce leaders face an impossible equation: deliver exponential growth with shrinking resources and rising costs. Traditional growth strategies—with 12-18 month implementation cycles and fragmented vendor relationships—can’t match today’s market velocity. While competitors capture

Read More
How the Link Guest Orders App Revolutionizes Customer Experience in eCommerce
Uncategorized

How the Link Guest Orders App Revolutionizes Customer Experience in eCommerce

In today’s competitive eCommerce world, customer experience is everything. Businesses must focus on delivering seamless, enjoyable experiences to keep customers coming back. One area where many eCommerce platforms struggle is managing guest orders. This is where the Link Guest Orders App steps in for BigCommerce store owners, revolutionizing the customer experience by linking guest orders

Read More