0

I want to override contact us post action using plugin as i have custom field in my contact form. I have created 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">
   <type name="Magento\Contact\Controller\Index\Post">
        <plugin name="custom_contact_action" type="Pos\Contact\Plugin\Post"/>
    </type> 
</config>

This is my Plugin file,

<?php

namespace Pos\Contact\Plugin;
class Post 
    {

 public function aroundExecute(\Magento\Contact\Controller\Index\Post $subject)
    {

        $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/index');
            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/index');
            return;
        }
    }



    }

When i submit the form then it shows me error ,

Fatal error: Uncaught Error: Call to undefined method Pos\Contact\Plugin\Post::getRequest() in /var/www/html/pospaper/app/code/Pos/Contact/Plugin/Post.php:10 Stack trace: #0 /var/www/html/pospaper/vendor/magento/framework/Interception/Interceptor.php(135): Pos\Contact\Plugin\Post->aroundExecute(Object(Magento\Contact\Controller\Index\Post\Interceptor), Object(Closure)) #1 /var/www/html/pospaper/vendor/magento/framework/Interception/Interceptor.php(153): Magento\Contact\Controller\Index\Post\Interceptor->Magento\Framework\Interception{closure}()

2 /var/www/html/pospaper/generated/code/Magento/Contact/Controller/Index/Post/Interceptor.php(26):

Magento\Contact\Controller\Index\Post\Interceptor->___callPlugins('execute', Array, NULL) #3 /var/www/html/pospaper/vendor/magento/framework/App/Action/Action.php(107): Magento\Contact\Controller\Index\Post\Interceptor->execute() #4 /var/www/html/pospaper/vendor/magento/module-contact/Controller/Index.php(67): Magento\Framework\App\Action\Action->dispatch(Object(Magento\Framework\Ap in /var/www/html/pospaper/app/code/Pos/Contact/Plugin/Post.php on line 10

Please help me!!!! Thanks in advanced!!

2

Try following code:


namespace Pos\Contact\Plugin;


class Post
{
    /**
     * @var \Magento\Framework\Controller\Result\RedirectFactory
     */
    protected $resultRedirectFactory;

    /**
     * @var \Magento\Framework\Message\ManagerInterface
     */
    protected $messageManager;

    /**
     * @var \Magento\Framework\Translate\Inline\StateInterface
     */
    protected $inlineTranslation;

    /**
     * @var \Magento\Framework\Mail\Template\TransportBuilder
     */
    protected $transportBuilder;

    /**
     * Core store config
     *
     * @var \Magento\Framework\App\Config\ScopeConfigInterface
     */
    protected $scopeConfig;

    /**
     * Post constructor.
     * 
     * @param \Magento\Framework\Controller\Result\RedirectFactory $resultRedirectFactory
     * @param \Magento\Framework\Message\ManagerInterface $messageManager
     * @param \Magento\Framework\Translate\Inline\StateInterface $inlineTranslation
     * @param \Magento\Framework\Mail\Template\TransportBuilder $transportBuilder
     * @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
     */
    public function __construct(
        \Magento\Framework\Controller\Result\RedirectFactory $resultRedirectFactory,
        \Magento\Framework\Message\ManagerInterface $messageManager,
        \Magento\Framework\Translate\Inline\StateInterface $inlineTranslation,
        \Magento\Framework\Mail\Template\TransportBuilder $transportBuilder,
        \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
    ) {
        $this->resultRedirectFactory = $resultRedirectFactory;
        $this->messageManager = $messageManager;
        $this->inlineTranslation = $inlineTranslation;
        $this->transportBuilder = $transportBuilder;
        $this->scopeConfig = $scopeConfig;
    }

    /**
     * @param \Magento\Contact\Controller\Index\Post $subject
     * @return $this|void
     */
    public function aroundExecute(
        \Magento\Contact\Controller\Index\Post $subject
    ) {

        $post = $subject->getRequest()->getPostValue();
        if (!$post) {
            return $this->resultRedirectFactory->create()->setPath('*/*/');
        }
        $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(\Magento\Contact\Controller\Index\Post::XML_PATH_EMAIL_TEMPLATE, $storeScope))
                ->setTemplateOptions(
                    [
                        'area' => \Magento\Framework\App\Area::AREA_FRONTEND,
                        'store' => \Magento\Store\Model\Store::DEFAULT_STORE_ID,
                    ]
                )
                ->setTemplateVars(['data' => $postObject])
                ->setFrom($this->scopeConfig->getValue(\Magento\Contact\Controller\Index\Post::XML_PATH_EMAIL_SENDER, $storeScope))
                ->addTo($this->scopeConfig->getValue(\Magento\Contact\Controller\Index\Post::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.')
            );
            return $this->resultRedirectFactory->create()->setPath('contact/index');
        } catch (\Exception $e) {
            $this->inlineTranslation->resume();
            $this->messageManager->addError(
                __('We can\'t process your request right now. Sorry, that\'s all we know.')
            );
            return $this->resultRedirectFactory->create()->setPath('contact/index');
        }
    }
}
1

Try this 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/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);
    }
}
  • This was not working for me!! i have tried this solution. – Sunny Rahevar Jun 20 '18 at 6:23
  • please remove var/generation folder. – Magento Developer Jun 20 '18 at 6:33
1

You can't access directly $this->getRequest() in plugin, You should access like below method

public function __construct(
        \Magento\Framework\App\RequestInterface $request

    ) {
        $this->_request = $request;

    }

Replace $post = $this->getRequest()->getPostValue(); by $post = $this->_request->getPostValue();

1

To add Custom field in email template please Follow Below Link

Add custom field to contact form Magento 2?

Overriding Block, Model, Controller in Magento2

app/code/Overriding/Magento2/etc/di.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/ObjectManager/etc/config.xsd">

       <preference for="Magento\Contact\Controller\Index\Post" type="Overriding\Magento2\Controller\Index\Post" />

</config>

app/code/Overriding/Magento2/Controller/Index/Post.php

public function execute()
    {
        if (!$this->isPostRequest()) {
            return $this->resultRedirectFactory->create()->setPath('*/*/');
        }
        try {
            $this->sendEmail($this->validatedParams());
            $this->messageManager->addSuccessMessage(
                __('Thanks for contacting us with your comments and questions. We\'ll respond to you very soon.')
            );
            $this->dataPersistor->clear('contact_us');
        } catch (LocalizedException $e) {
            $this->messageManager->addErrorMessage($e->getMessage());
            $this->dataPersistor->set('contact_us', $this->getRequest()->getParams());
        } catch (\Exception $e) {
            $this->logger->critical($e);
            $this->messageManager->addErrorMessage(
                __('An error occurred while processing your form. Please try again later.')
            );
            $this->dataPersistor->set('contact_us', $this->getRequest()->getParams());
        }
        return $this->resultRedirectFactory->create()->setPath('contact-us');
    }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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