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 Add Tooltip in Checkout Shipping Field in Magento 2?

Hello Magento Friends, In today’s blog, I will explain How to Add Tooltip in Checkout…

3 days ago

How to Integrate and Use MongoDB with Laravel?

MongoDB is a popular NoSQL database that offers flexibility and scalability when handling modern web…

4 days ago

NodeJS | Callback Function

In NodeJS, callbacks empower developers to execute asynchronous operations like reading files, handling requests, and…

5 days ago

How to Show SKU in Order Summary in Magento 2?

Hello Magento Friends, In today’s blog, we will learn How to Show SKU in Order…

7 days ago

Best Colors to Use for CTA Buttons

The "Buy Now" and "Add to Cart" buttons serve as the primary call-to-action (CTA) elements…

1 week ago

Magento 2: How to Save Custom Field Value to quote_address for Multi-Shipping Orders

Hello Magento Friends, In Magento 2, the checkout process allows customers to choose multiple shipping…

1 week ago