Magento – Is it possible to redirect the Magento 2 Contact Form without a custom module

contact-usmagento2redirect-url

I'm trying to get the Magento 2 Contact form to redirect not to /contact/index but someplace else.
Here is what I have so far:

We use a custom theme, in which I have created a the following folders

Magento_Contact
-email
-submitted_form.html
-templates
- form.phtml

I've edited the form.phtml to add / edit the fields as required.

I've created a content block and added the form to it with:

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

And I've created a CMS Page with this block in it, using

{{block class="Magento\\Cms\\Block\\Block" block_id="myContact"}}

Now I want to the user to stay on that CMS Page after submitting the form, so I presume I will need to change $this->_redirect('contact/index'); to $this->_redirect('*/*/'); in the modules post controller.

I was wondering if there wasn't a quicker way to add the redirect, maybe as a block comment or similar.

Thank you.

Best Answer

You can implement Magento 2 after method plugin for execute method of Post controller of Contact module. And create CMS page with 'contact/thanks' URL and redirect to the page in your plugin. But in that case you need custom module to place your plugin.

<?php

namespace YourModule\ContactUsRedirect\Plugin;

class PostPlugin
{
    /**
     * @var \Magento\Framework\App\Request\DataPersistorInterface
     */
    private $_dataPersistor;

    /**
     * @var \Magento\Framework\App\Response\RedirectInterface
     */
    private $_redirect;

    /**
     * PostPlugin constructor.
     * @param \Magento\Framework\App\Request\DataPersistorInterface $dataPersistor
     * @param \Magento\Framework\App\Response\RedirectInterface $redirect
     */
    public function __construct(
        \Magento\Framework\App\Request\DataPersistorInterface $dataPersistor,
        \Magento\Framework\App\Response\RedirectInterface $redirect
    ) {
        $this->_dataPersistor = $dataPersistor;
        $this->_redirect = $redirect;
    }

    public function afterExecute(\Magento\Contact\Controller\Index\Post $subject, $result)
    {
        $post = $subject->getRequest()->getPostValue();

        if (!$post) {
            return;
        }

        if (!$this->_dataPersistor->get('contact_us')) {
            $this->_redirect->redirect($subject->getResponse(), 'contact/thanks');
        }
    }
}