How to Override or Rewrite Controller in Magento 2

Updating a feature in Magento can sometimes pose challenges due to the complexities of the application’s core functions. However, customizing Magento often involves overriding controllers to ensure they match specific requirements. The good news is there’s a simpler approach available that can save you time and effort in this article. We’ll guide you through the steps needed to overwrite or rewrite a controller in Magento 2, enabling you to adjust the platform to your exact needs easily.

How to rewrite and override controller in Magento 2

To rewrite controller and override, you can do it by using preference. It mean that you need to put a rule in your router config using before attribute.

Open Mageplaza/HelloWorld/etc/routes.xml insert the following block of code inside <config> tag rewrite controller in Magento 2

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

<router id="standard">
    <route id="mageplaza" frontName="hello">
       <module name="Mageplaza_HelloWorld" before="Magento_Customer" />
    </route>
</router>

</config>

This will completely change controller/action of module Magento_Customer with your controller code, so you should extend rewrite controller and make a change on the function which you want. Also, the controller and action in your module must have same name with rewrite controller/action.

Create Mageplaza/HelloWorld/etc/di.xml and add the code below.

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <preference for="Magento\Customer\Controller\Account\Create" type="Mageplaza\HelloWorld\Controller\Account\Create" />
</config>

For example, if you want to rewrite controller: Magento\Customer\Controller\Account\Create.php You have to register a router like above and create a controller:

NameSpace\ModuleName\Controller\Account\Create.php

Content of Create.php file:

namespace Mageplaza\HelloWorld\Controller\Account;

use Magento\Customer\Model\Registration;
use Magento\Customer\Model\Session;
use Magento\Framework\View\Result\PageFactory;
use Magento\Framework\App\Action\Context;

class Create extends \Magento\Customer\Controller\AbstractAccount
{
    /** @var Registration */
    protected $registration;

    /**
     * @var Session
     */
    protected $session;

    /**
     * @var PageFactory
     */
    protected $resultPageFactory;

    /**
     * @param Context $context
     * @param Session $customerSession
     * @param PageFactory $resultPageFactory
     * @param Registration $registration
     */
    public function __construct(
        Context $context,
        Session $customerSession,
        PageFactory $resultPageFactory,
        Registration $registration
    ) {
        $this->session = $customerSession;
        $this->resultPageFactory = $resultPageFactory;
        $this->registration = $registration;
        parent::__construct($context);
    }

    /**
     * Customer register form page
     *
     * @return \Magento\Framework\Controller\Result\Redirect|\Magento\Framework\View\Result\Page
     */
    public function execute()
    {
        if ($this->session->isLoggedIn() || !$this->registration->isAllowed()) {
            /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */
            $resultRedirect = $this->resultRedirectFactory->create();
            $resultRedirect->setPath('*/*');
            return $resultRedirect;
        }

        /** @var \Magento\Framework\View\Result\Page $resultPage */
        $resultPage = $this->resultPageFactory->create();
        return $resultPage;
    }
}

Verification and enabling of the module Enable the module and clean the cache by running the following commands:

bin/magento module:enable Vendor_ModuleName
bin/magento setup:upgrade
bin/magento cache:flush

Now, your custom controller is active, and you can access it using the URL: http://yourmagento.com/hello/account\create

If you got this error message: Exception printing is disabled by default for security reasons, this topic may help.


Magento 2 extensions

Magento 2 extensions

Allow you to achieve more with your online store

Check it out!


In conclusion

This how to override or rewrite controller in Magento 2 guide provides a structured approach to rewriting or overriding a controller in Magento 2, ensuring that your custom logic is implemented correctly. Remember to test your changes thoroughly in a development environment before deploying to production. If you need further assistance or have specific questions, feel free to ask!

Related Post

Image Description
With over a decade of experience crafting innovative tech solutions for ecommerce businesses built on Magento, Jacker is the mastermind behind our secure and well-functioned extensions. With his expertise in building user-friendly interfaces and robust back-end systems, Mageplaza was able to deliver exceptional Magento solutions and services for over 122K+ customers around the world.

People also searched for

  • magento 2 rewrite controller
  • magento 2 override controller
  • overriding controller Magento 2
  • rewrite controller in magento 2
  • how to rewrite controller
  • 2.3.x, 2.4.x
x