How to Create Custom Form in Magento 2 Frontend

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.

Magento 2 Mobile APP

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.

Frontend_display

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

Previous Article

How to Add Product Attribute to Sales Rules Conditions in Magento 2

Next Article

How to Get Region Code by Region ID in Magento 2

View Comments (5)
  1. Hi,
    i followed the steps and can´t get the form visible in frontend.
    How to call the URL of the form? mydomain.com/extension/index/index or…

    Greets, Jan

    1. Please check you have created other basic files for the extension, and the extension is enabled in your store.
      With that URL, you need to replace your URL which you have created using XML.

Leave a Comment

Your email address will not be published. Required fields are marked *

Get Connect With Us

Subscribe to our email newsletter to get the latest posts delivered right to your email.
Pure inspiration, zero spam ✨