Magento – Contact form after submission not redirecting to cms page Magento 2

contact-formmagento2redirect

I have created contact us page and called contact form block in content.When user submit for it redirect to contact/index instead of redirecting to current cms page that is contact-us.

I searched on internet but didn't found solution for magento 2.

Here is the code for contact form block:

   {{block class="Magento\\Contact\\Block\\ContactForm" template="Magento_Contact::form-contact.phtml"}}

Can anyone suggest me how can i redirect it to contact-us page instead of contact/index.

UPDATE

Here is my form-contact.phtml code:

    <?php
        /**
         * Copyright © 2015 Magento. All rights reserved.
         * See COPYING.txt for license details.
         */

        // @codingStandardsIgnoreFile

        ?>
        <form class="form contact"
              action="<?php /* @escapeNotVerified */ echo $block->getFormAction(); ?>"
              id="contact-form"
              method="post"
              data-hasrequired="<?php /* @escapeNotVerified */ echo __('* Required Fields') ?>"
              data-mage-init='{"validation":{}}'>
            <fieldset class="fieldset">
                <div class="title-bonus-page">
                    <h2><?php /* @escapeNotVerified */ echo __('Send your comments') ?></h2>
                </div>
                <div class="col-sm-4"> 
                    <div class="left-input">
                        <div class="field name required">

                            <div class="control">
                                <input placeholder="<?php echo __('Your Name*')?>" name="name" id="name" title="<?php /* @escapeNotVerified */ echo __('Name') ?>" value="<?php echo $block->escapeHtml($this->helper('Magento\Contact\Helper\Data')->getUserName()) ?>" class="input-text" type="text" data-validate="{required:true}"/>
                                <i class="fa fa-user"></i>
                            </div>
                        </div>
                        <div class="field email required">

                            <div class="control">
                                <input placeholder="<?php echo __('Your Email*')?>" name="email" id="email" title="<?php /* @escapeNotVerified */ echo __('Email') ?>" value="<?php echo $block->escapeHtml($this->helper('Magento\Contact\Helper\Data')->getUserEmail()) ?>" class="input-text" type="email" data-validate="{required:true, 'validate-email':true}"/>
                               <i class="fa fa-envelope-o" aria-hidden="true"></i>
                            </div>
                        </div>
                        <div class="field telephone">

                            <div class="control">
                                <input placeholder="<?php echo __('Your Phone')?>" name="telephone" id="telephone" title="<?php /* @escapeNotVerified */ echo __('Phone Number') ?>" value="" class="input-text" type="text" data-validate="{required:true}"/>
                                <i class="fa fa-phone"></i>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-sm-8"> 
                    <div class="field comment required">
                        <div class="control">
                            <textarea placeholder="<?php echo __('Your Message*')?>" name="comment" id="comment" title="<?php /* @escapeNotVerified */ echo __('What’s on your mind?') ?>" class="input-text" cols="5" rows="3" data-validate="{required:true}"></textarea>
                            <i class="fa fa-file-text-o" aria-hidden="true"></i>
                        </div>
                    </div>
                    <?php echo $block->getChildHtml('form.additional.info'); ?>
                    <div class="actions-toolbar">
                        <div class="primary">
                            <input type="hidden" name="hideit" id="hideit" value="" />
                            <button type="submit" title="<?php /* @escapeNotVerified */ echo __('Send Message') ?>" class="action submit primary">
                                <span><?php /* @escapeNotVerified */ echo __('Send Message') ?></span>
                            </button>
                        </div>
                    </div>
                  </div>
            </fieldset>
        </form>

Update 2

The output of $block->getFormAction() is

 http://www.siteurl/contact/index/post/

Best Answer

Contact Post Controller needs to be overridden here, because by default it redirects to contact/index
$this->_redirect('contact/index'); needs to be changed to $this->_redirect('cms-page-url-key'); in file vendor/magento/module-contact/Controller/Index/Post.php

Code for controller override is as follows :

app/code/Custom/Contact/registration.php

<?php
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Custom_Contact',
    __DIR__
);

app/code/Custom/Contact/etc/module.xml

<?xml version="1.0" encoding="UTF-8"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Custom_Contact" setup_version="1.0.0">
        <sequence>
            <module name="Magento_Contact"/>
        </sequence>
    </module>
</config>

app/code/Custom/Contact/etc/di.xml

<?xml version="1.0" encoding="UTF-8"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <preference for="Magento\Contact\Controller\Index\Post" type="Custom\Contact\Controller\Index\Post" />
</config>

app/code/Custom/Contact/Controller/Index/Post.php

<?php
namespace Custom\Contact\Controller\Index;

use Magento\Framework\App\Request\DataPersistorInterface;
use Magento\Framework\App\ObjectManager;

class Post extends \Magento\Contact\Controller\Index\Post
{
    /**
     * @var DataPersistorInterface
     */
    private $dataPersistor;

    /**
     * Post user question
     *
     * @return void
     * @throws \Exception
     */
    public function execute()
    {
        $post = $this->getRequest()->getPostValue();
        if (!$post) {
            $this->_redirect('*/*/');
            return;
        }

        $this->inlineTranslation->suspend();
        try {
            $postObject = new \Magento\Framework\DataObject();
            $postObject->setData($post);

            $error = false;

            if (!\Zend_Validate::is(trim($post['name']), 'NotEmpty')) {
                $error = true;
            }
            if (!\Zend_Validate::is(trim($post['comment']), 'NotEmpty')) {
                $error = true;
            }
            if (!\Zend_Validate::is(trim($post['email']), 'EmailAddress')) {
                $error = true;
            }
            if (\Zend_Validate::is(trim($post['hideit']), 'NotEmpty')) {
                $error = true;
            }
            if ($error) {
                throw new \Exception();
            }

            $storeScope = \Magento\Store\Model\ScopeInterface::SCOPE_STORE;
            $transport = $this->_transportBuilder
                ->setTemplateIdentifier($this->scopeConfig->getValue(self::XML_PATH_EMAIL_TEMPLATE, $storeScope))
                ->setTemplateOptions(
                    [
                        'area' => \Magento\Backend\App\Area\FrontNameResolver::AREA_CODE,
                        'store' => \Magento\Store\Model\Store::DEFAULT_STORE_ID,
                    ]
                )
                ->setTemplateVars(['data' => $postObject])
                ->setFrom($this->scopeConfig->getValue(self::XML_PATH_EMAIL_SENDER, $storeScope))
                ->addTo($this->scopeConfig->getValue(self::XML_PATH_EMAIL_RECIPIENT, $storeScope))
                ->setReplyTo($post['email'])
                ->getTransport();

            $transport->sendMessage();
            $this->inlineTranslation->resume();
            $this->messageManager->addSuccess(
                __('Thanks for contacting us with your comments and questions. We\'ll respond to you very soon.')
            );
            $this->getDataPersistor()->clear('contact_us');
            $this->_redirect('contact-us');
            return;
        } catch (\Exception $e) {
            $this->inlineTranslation->resume();
            $this->messageManager->addError(
                __('We can\'t process your request right now. Sorry, that\'s all we know.')
            );
            $this->getDataPersistor()->set('contact_us', $post);
            $this->_redirect('contact-us');
            return;
        }
    }

    /**
     * Get Data Persistor
     *
     * @return DataPersistorInterface
     */
    private function getDataPersistor()
    {
        if ($this->dataPersistor === null) {
            $this->dataPersistor = ObjectManager::getInstance()
                ->get(DataPersistorInterface::class);
        }

        return $this->dataPersistor;
    }

}

Here contact-us is the cms page url key.

Related Topic