6

how to Override contact controller in custom module?

venoder/magento/module-contact/Controller/Index.php
1
  • 5
    if you want answer your own question first post the question then answer it Commented Aug 30, 2016 at 4:52

1 Answer 1

7

create di.xml file in your custom module

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

add below code in di.xml file.

<?xml version="1.0"?>
<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="Contact\Custom\Controller\Index\ExtendIndex" />
</config>

create ExtendIndex.php file /magento2/app/code/Contact/Controller/Index/ExtendIndex.php

<?php
     namespace Contact\Custom\Controller\Index;
class ExtendIndex extends \Magento\Contact\Controller\Index\Post
{
    /**
     * Index action
     *
     * @return $this
     */
    public function execute($coreRoute = null)
    {


        $this->messageManager->addSuccess('Message from new controller.');
        return parent::execute($coreRoute);
    }
}
2
  • 1
    To extend behavior of existing methods, plugins are the preferred method. The main advantage is that you can have multiple different plugins per class and even per method. For an example with a controller, see the linked duplicate: magento.stackexchange.com/questions/68793/… Commented Aug 30, 2016 at 6:22
  • @Karamdeep This is not working for me. the changes are not getting reflected. It is taking the success message from core itself
    – Nafsss
    Commented Aug 12, 2019 at 9:57

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