Magento Tutorials

How to Create Custom Form in Magento 2 Frontend

Hello Magento Friends,

How are you guys? Today I am going to explain How to Create Custom Form in Magento 2. If you missed checking out our previous blog, How to Manage Customers and Customers Group in Magento 2.

Introduction:

Customer data is very useful for store owners to create a great user experience for their store. Online store owners make every possible effort to collect customer data as user experience is the primary goal of any business. With these data, the store owners can provide a personalized experience to their customers.

Forms are a great way to gather customer information. Default Magento 2 form has limited fields. But one can create a custom form in Magento 2 as per the requirement. With the help of the below code, you can Create Custom Form in Magento 2 Frontend.

Steps to Create Custom Form in Magento 2 Frontend:

Step 1: Update code in file Form.php at app\code\Magecomp\Extension\Block

<?php

namespace Magecomp\Extension\Block\Customer;

use Magento\Framework\View\Element\Template;

use Magento\Backend\Block\Template\Context;

use Magento\Directory\Model\ResourceModel\Country\CollectionFactory;

class Form extends Template

{

&nbsp;&nbsp;&nbsp;protected $_countryCollectionFactory;

public function __construct(CollectionFactory $countryCollectionFactory,Context $context, array $data = [])

{

&nbsp;&nbsp;&nbsp;$this->_countryCollectionFactory = $countryCollectionFactory;

&nbsp;&nbsp;&nbsp;parent::__construct($context, $data);

}

public function getCountryCollection()

{

&nbsp;&nbsp;&nbsp;$collection = $this->_countryCollectionFactory->create()->loadByStore();

&nbsp;&nbsp;&nbsp;return $collection;

}

public function getCountries()

{

&nbsp;&nbsp;&nbsp;return $this->getCountryCollection()->toOptionArray();

}

}

?>

Step 2: Update code in file Index.php at app\code\Magecomp\Extension\Controller\Form\Index.php

<?php

namespace Magecomp\Extension\Controller\Form;

class Index extends \Magento\Framework\App\Action\Action

{
    public function execute()
    {
            $this->_view->loadLayout();
            $this->_view->renderLayout();
    }
}

Step 3: Update code in file form.phtml at app\code\Magecomp\Extension\view\frontend\templates\

<div id="custom-form">

   <form class="form contact"

         action="<?php echo $this->getUrl('extension/index/save', ['_secure' => true]);?>"

         id="custom-form"

         method="post"

         data-hasrequired="<?php  echo __('* Required Fields') ?>"

         data-mage-init='{"validation":{}}'>

       <input type="hidden" name="cproduct_id" id="cproduct_id" value="0" />

       <fieldset class="fieldset">

           <legend class="legend"><span><?php  echo __("Query Detail") ?></span></legend><br />

           <div class="field name required">

               <label class="label" for="name"><span><?php  echo __('Name') ?></span></label>

               <div class="control">

                   <input name="name" id="name" title="<?php  echo __('Name') ?>" class="input-text" type="text" data-validate="{required:true}"/>

               </div>

           </div>

           <div class="field email required">

               <label class="label" for="email"><span><?php  echo __('Email') ?></span></label>

               <div class="control">

                   <input name="email" id="email" title="<?php  echo __('Email') ?>" class="input-text" type="email" data-validate="{required:true, 'validate-email':true}"/>

               </div>

           </div>

           <div class="field country required">

               <label class="label" for="country"><span><?php echo __('Country') ?></span></label>

               <div class="control">

                   <select name="country" id="country" data-validate="{required:true, 'validate-select':true}">

                       <option value=""><?php echo __('Please Select')?></option>

                       <?php

                       $countries = $block->getCountries();

                       foreach ( $countries as $countryKey => $country )

                       {

                           if($country['value'] != '')

                           {?>

                               <option value="<?php echo $country['value'];?>"><?php echo $country['label'];?></option>

                           <?php }

                       }

                       ?>

                   </select>

               </div>

           </div>

           <div class="field telephone">

               <label class="label" for="telephone"><span><?php  echo __('Phone Number') ?></span></label>

               <div class="control">

                   <input name="telephone" id="telephone" title="<?php  echo __('Phone Number') ?>" value="" class="input-text" type="text" />

               </div>

           </div>

           <div class="field comment required">

               <label class="label" for="comment"><span><?php  echo __('What’s on your mind?') ?></span></label>

               <div class="control">

                   <textarea name="comment" id="comment" title="<?php  echo __('What’s on your mind?') ?>" class="input-text" cols="5" rows="3" data-validate="{required:true}"></textarea>

               </div>

           </div>

       </fieldset>

       <div class="actions-toolbar">

           <div class="primary">

               <input type="hidden" name="hideit" id="hideit" value="" />

               <button type="submit" title="<?php  echo __('Submit') ?>" class="action submit primary" id="custom_btn">

                   <span><?php  echo __('Submit') ?></span>

               </button>

           </div>

       </div>

   </form>

</div>

That’s it. By following the above steps, your custom form will be displayed in the frontend as below image.

 

Conclusion:

Hence, you have successfully created a custom form in Magento 2 as per your requirements. In case of any doubts, let me know in the comment section. Share the article further and stay tuned!

Happy Reading

Click to rate this post!
[Total: 31 Average: 3.3]
Dhiren Vasoya

Dhiren Vasoya is a Director and Co-founder at MageComp, Passionate 🎖️ Certified Magento Developer👨‍💻. He has more than 9 years of experience in Magento Development and completed 850+ projects to solve the most important E-commerce challenges. He is fond❤️ of coding and if he is not busy developing then you can find him at the cricket ground, hitting boundaries.🏏

View Comments

Recent Posts

How to Integrate ChatGPT with Laravel Application?

In this guide, we'll explore how to integrate ChatGPT, an AI-powered chatbot, with a Laravel…

43 mins ago

What are Net Sales? How to Calculate Your Net Sales?

In the world of business, understanding financial metrics is crucial for making informed decisions and…

2 days ago

Magento 2 Extensions Digest April 2024 (New Release & Updates)

Welcome to the MageComp Monthly Digest, where we bring you the latest updates, releases, and…

2 days ago

The ABCs of Geofencing: Definition, Features and Uses

In this era, businesses are always on the lookout for ways to engage with their…

3 days ago

How to Delete Product Variant in a Shopify Remix App using GraphQL Mutations?

Managing a Shopify store efficiently involves keeping your product catalog organized. This includes removing outdated…

4 days ago

6 Innovative Tools Revolutionizing E-Commerce Operations

E-commerce has transformed the way consumers shop for products and services and interact with businesses.…

6 days ago