5

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/
6
  • Share code of template Magento_Contact::form-contact.phtml Commented Dec 7, 2016 at 10:33
  • Thanks for your response. I updated my question above. Please check.
    – Thomas
    Commented Dec 7, 2016 at 10:46
  • What is output of" echo $block->getFormAction()" i mean what is action URL of your form Commented Dec 7, 2016 at 11:28
  • 1
    I updated my question above. Please check.
    – Thomas
    Commented Dec 7, 2016 at 11:31
  • After successfully submit your form url look like, siteurl/contact/index Commented Dec 7, 2016 at 12:55

3 Answers 3

8

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.

8
  • 5
    You can change the redirect to $this->_redirect->getRefererUrl() to redirect to the previous page so you don't need to know what the url key is. Commented Jun 22, 2017 at 9:09
  • I have fetch some error like Undefined property:$inlineTranslation so can you provide solution for this error.
    – meet
    Commented Mar 29, 2018 at 6:49
  • @meet There seems to be some typo, the error means variable $inlineTranslation is not defined. Kindly share full error report and code. Commented Mar 29, 2018 at 6:52
  • 1
    Error show like below 1 exception(s): Exception #0 (Exception): Notice: Undefined property: Custom\Contact\Controller\Index\Post\Interceptor::$inlineTranslation in /app/code/Custom/Contact/Controller/Index/Post.php on line 33 Exception #0 (Exception): Notice: Undefined property: Custom\Contact\Controller\Index\Post\Interceptor::$inlineTranslation in /app/code/Ktpl/CmsPages/Controller/Index/Post.php on line 33 #0 /app/code/Custom/Contact/Controller/Index/Post.php(33): Magento\Framework\App\ErrorHandler->handler(8, 'Undefined prope...', '/var/www/vhosts...', 33, Array)
    – meet
    Commented Mar 29, 2018 at 7:00
  • @meet Kindly share code for file app/code/Custom/Contact/Controller/Index/Post.php Commented Mar 29, 2018 at 7:05
0

I'm not sure about your Controller. However, your form is missing form key $block->getFormKey():

<input name="form_key" type="hidden" value="<?php /* @escapeNotVerified */ echo $block->getFormKey(); ?>" />
0

This was a great help getting me to the correct location, I found that all I had to do was create a new confirmation page, then change the file confirmation path (below).

Here is where I made my new confirmation path changes:
Line: 77
Line: 85

vendor/magento/module-contact/Controller/Index/Post.php

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.