In Magento 2, the controller is responsible for handling incoming requests, and it’s the backbone of Magento routing implementation.
When you are working on the custom modules in Magento 2, it’s very important to override core module files instead of making changes to it directly. Overriding the controller in Magento 2 gives you the flexibility to change the core functionality as per your Magento 2 module development requirements.
By following the steps given below you can override the core controller of Magento 2 easily. In this example,you will override default 404 page and display your custom 404 page if the category URL is invalid.
The code is available in GitHub at https://goo.gl/FJHpL3
How To Override a Controller In Magento 2?
Create a custom module based on the Magento 2 structure in the folder app/code
Ex: Magento 2 root directory/app/code/DCKAP/Custom404Page/
Create a module.xml file in the below path to define your Magento 2 extension
Magento 2 root directory/app/code/DCKAP/Custom404Page/etc/module.xml
Create di.xml file in the below path to refer overriding class
Magento 2 root directory/app/code/DCKAP/Custom404Page/etc/di.xml
Now DCKAP\Custom404Page\Controller\Category\View will be used to override
Create routes.xml file in the below path for your custom controller file.
Magento 2 root directory/app/code/DCKAP/Custom404Page/etc/frontend/routes.xml
Create view.php file in the below path to define an overriding controller class
Magento 2 root directory/app/code/DCKAP/Custom404Page/Controller/Category
Create the custom controller file to show the custom 404 page for the invalid category URL. Create the custom controller file in the following path…
Magento 2 root directory/app/code/DCKAP/Custom404Page/Controller/CategoryNoRoute/Index.php
Create block file for the custom 404 page in the following path…
Magento 2 root directory/app/code/DCKAP/Custom404Page/Block/CategoryNoRoute.php
Create layout file in the below path for the custom 404 page.
Magento 2 root directory/app/code/DCKAP/Custom404Page/view/frontend/layout/ custom404page_categorynoroute_index.xml
Create template file in the below path for the custom 404 page.
Magento 2 root directory/app/code/DCKAP/Custom404Page/view/frontend/templates/ categorynoroute.phtml
After completing the above steps, run the below Magento 2 upgrade comment in the command prompt.
After running the above comment , clear all the Magento cache and check on the Magento 2 admin side whether the extension installed successfully.
Check the browser whether the custom 404 controller is working fine, by providing a wrong category URL.
In the above URL, no category exists with the id 100.
Hope this blog helped you understand how to override controllers in Magento 2.
You might also be interested in our other Magento 2 blogs: