Magento 2 Custom Module – How to Submit a Form

contact-formmagento-2.1

I created a custom module. There is a form which user submit. I want to capture the post data. So how to create a post route ?

This is my routes.xml

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../lib/internal/Magento/Framework/App/etc/routes.xsd">
<router id="standard">
    <route id="contactus" frontName="contactus">
        <module name="My_ContactUs" />
    </route>
</router>

And I have only 1 controller which display the form.

Best Answer

create a controller Save.php and copy paste in your module.

<?php
namespace [Namespace]\[ModuleName]\Controller\Index;


class Save extends \Magento\Framework\App\Action\Action
{

    /**
     * @var \Magento\Framework\View\Result\PageFactory
     */
    protected $resultPageFactory;


    /**
     * @param \Magento\Framework\App\Action\Context $context
     * @param \Magento\Framework\View\Result\PageFactory $resultPageFactory
     */
    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Framework\View\Result\PageFactory $resultPageFactory
    )
    {
        $this->resultPageFactory = $resultPageFactory;
        parent::__construct($context);
    }

    /**
     * Default customer account page
     *
     * @return void
     */
    public function execute()
    {

        /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */
        $resultRedirect = $this->resultRedirectFactory->create();

        try{

            $request = $this->getRequest()->getParams();           
            $email = $request['email'];
            $this->resultPageFactory->create();
            return $resultRedirect->setPath('contactus/index/index');

        }catch (\Exception $e){
            $this->messageManager->addExceptionMessage($e, __('We can\'t submit your request, Please try again.'));
            $this->_objectManager->get('Psr\Log\LoggerInterface')->critical($e);
            return $resultRedirect->setPath('contactus/index/index');
        }

    }

}
?>

create save.phtml file from [Namespace]/[ModuleName/view/frontend/templates and copy paste it below code.

  <?php
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $storeManager = $objectManager->create('\Magento\Store\Model\StoreManagerInterface');
    $baseURL_l = $social_image_url = $storeManager->getStore()->getBaseUrl();
    ?>
    <form action="<?php /* @escapeNotVerified */ echo $baseURL_l . 'contactus/index/save' ?>" method="post" id="form-validate" enctype="multipart/form-data" autocomplete="off" data-mage-init='{"validation":{}}' data-hasrequired="<?php /* @escapeNotVerified */ echo __('* Required Fields') ?>">
        <div class="field required">
            <label for="email_address" class="label"><span><?php /* @escapeNotVerified */ echo __('Email') ?></span><span class="span">*</span></label>
            <div class="control">
                <input type="email" name="email" autocomplete="email" id="email_address" value="" title="<?php /* @escapeNotVerified */ echo __('Email') ?>" class="input-text" data-validate="{required:true, 'validate-email':true}">
            </div>
        </div><br/>
 <div class="primary">
            <button type="submit" class="action submit primary" title="<?php /* @escapeNotVerified */ echo __('Submit') ?>"><span><?php /* @escapeNotVerified */ echo __('Submit') ?></span></button>
        </div>
    </form>

Now enter the email and hit the Submit button you will get the email $request['email'] this variable. So you can do it from your logic.

Related Topic