Advertisement

Facebook

How to Override Magento 2 Contact Us Post Action Using Before, After, and Around Plugins

How to Override Magento 2 Contact Us Post Action Using Before, After, and Around Plugins

The Contact Us form in Magento 2 is one of the easiest ways for customers to reach out to your business. But what if you want to make it more personalized or add extra functionality? For example, maybe you want to log the submissions, validate some fields, or change the message shown to customers after they submit the form.

This is where Magento 2 plugins come into play! Plugins let you modify the behavior of Magento without changing its core files. This means your changes will stay safe, even when you update Magento later.

In this guide, we’ll walk you through how to customize the Contact Us form’s post action using before, after, and around plugins.

What Are Plugins in Magento 2?

Plugins are tools in Magento 2 that let you add or change functionality in public methods of classes. You don’t have to touch the core files, which makes them safe and future-proof. There are three types of plugins you can use:

  • Before Plugin: Runs before the original method.
  • After Plugin: Runs after the original method.
  • Around Plugin: Wraps around the method and gives you complete control.

Why Customize the Contact Us Post Action?

The Contact Us post action handles what happens when someone submits the Contact Us form. Here are some examples of why you might want to customize it:

  • Add custom validation
  • Log submissions
  • Change email behavior
  • Modify messages

Instead of editing Magento’s core files, which can cause problems later, we’ll use plugins to make these changes safely.

Step-by-Step Guide to Override the Contact Us Post Action

Step 1: Create the registration.php file at app/code/VendorName/ModuleName and add the following code:

<?php
use Magento\Framework\Component\ComponentRegistrar;

ComponentRegistrar::register(ComponentRegistrar::MODULE, 'VendorName_ModuleName', __DIR__);

Step 2: Create the module.xml file at app/code/VendorName/ModuleName/etc and add the following code:

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

Step 3: Create the di.xml file at app/code/VendorName/ModuleName/etc and add the following code:

<?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="customize_contact_post" type="VendorName\ModuleName\Plugin\ContactPostPlugin" sortOrder="10" disabled="false" />  
    </type>  
</config>

In this file, we tell Magento which class we want to modify and which plugin will handle it.

Step 4: Create the ContactPostPlugin.php file at app/code/VendorName/ModuleName/Plugin and add the following code:

<?php

namespace VendorName\ModuleName\Plugin;

use Magento\Framework\Controller\Result\RedirectFactory;
use Magento\Framework\Message\ManagerInterface;
use Magento\Contact\Model\MailInterface;

class ContactPostPlugin
{
    private $resultRedirectFactory;
    private $messageManager;
    private $mail;

    public function __construct(
        RedirectFactory $resultRedirectFactory,
        ManagerInterface $messageManager,
        MailInterface $mail
    ) {
        $this->resultRedirectFactory = $resultRedirectFactory;
        $this->messageManager = $messageManager;
        $this->mail = $mail;
    }

    // Before Plugin: Modify input data before execution
    public function beforeExecute(\Magento\Contact\Controller\Index\Post $subject)
    {
        $data = $subject->getRequest()->getPostValue();
        $this->messageManager->addSuccessMessage(__('Your inquiry has been logged.'));
        if (empty($data['telephone'])) {
            throw new \Magento\Framework\Exception\LocalizedException(__('Telephone is required.'));
        }

        return null;
    }

    // After Plugin: Perform actions after execution
    public function afterExecute(\Magento\Contact\Controller\Index\Post $subject, $result)
    {
        $this->messageManager->addSuccessMessage(__('Your inquiry has been logged.'));
        return $result;
    }

    // Around Plugin: Complete control over execution
    public function aroundExecute(\Magento\Contact\Controller\Index\Post $subject, \Closure $proceed)
    {
        try {
            $result = $proceed();
            $this->messageManager->addSuccessMessage(__('Thank you for contacting us!'));
            return $result;
        } catch (\Exception $e) {
            $this->messageManager->addErrorMessage(__('Something went wrong. Please try again.'));
        }

        return $this->resultRedirectFactory->create()->setPath('*/*/');
    }
}

Step 5: Run the Commands and Test Your Module

After creating the necessary files, run the following commands to enable and test your module:

php bin/magento module:enable VendorName_ModuleName
php bin/magento setup:upgrade
php bin/magento setup:static-content:deploy -f
php bin/magento setup:di:compile
php bin/magento cache:clean

Test the Contact Us form to verify that your customizations are working as expected.The test URL: https://www.example.com/contact

Conclusion

Using before, after, and around plugins to customize the Contact Us post action in Magento 2 offers a powerful, efficient, and safe way to enhance the Contact Us form. This method allows you to add custom features like validation, logging, and personalized messaging, all while preserving the integrity of Magento's core code. Plugins ensure your changes remain compatible with future Magento updates, providing a future-proof solution.

By adopting this approach, you can enhance customer communication, streamline your processes, and maintain a clean, efficient Magento store. For more expert tips on Magento 2 customization, Contact Us form enhancements, and other Magento solutions, stay tuned to our blog!

Post a Comment

0 Comments

Buy Me A Coffee