×



















    Get a Free Consultation

    Search for:

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

    Last Updated | August 24, 2024

    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.


    folio-social-logo
    About

    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.