Get FREE $25 Hosting for Managed Magento Hosting. Use Coupon: MGT25 Avail Now
Magento 2 Tutorials

How to Override Model in Magento 2

override model in magento 2

A Model is an important part of MVC (Model-View-Controller) pattern as it represents the data of the application. In the same way, Models have a very useful role in Magento as well. Since editing Model from the core files is not a good practice, you should instead rewrite Model in Magento 2!

Hence, in this tutorial, I am going to teach you how to override models in Magento 2. What you need is a custom module to do that, so let’s begin.

Steps to Follow

  • Create Directories
  • Configuration of Module
  • Registration of Module
  • Override di.xml
  • Override Product.php
  • Launch SSH and Run Commands

Create Directories

In the root directory of your store, create the following directories in the same manner shown below:

directory model

Configuration of Module

Create module.xml in app/code/Magenticians/Moduleproduct/etc and add the following code in it:


Registration of Module

Create registration.php in app/code/Magenticians/Moduleproduct and add the following code in it:

Override di.xml

Create di.xml  in app/code/Magenticians/Moduleproduct/etc in order to specify which model to override by using <preference for=””>  and <preference type=””>.

Add the following code in it: The purpose of creating this file is to override di.xml file

<preference for=””> Which Model to override.

<preference type=””> Where to override.

Override Product.php

Now create Product.php in app/code/Magenticians/Moduleproduct/Model/Catalog and add the following code in i

In the code above, I have overriden the product name and product SKU.

Launch SSH and Run Commands

Run the following commands in the Magento 2 root directory:

Now it’s time to check results! Go to the product page and you should see this:

result override model

Looking for the most reliable hosting platform?

Then, do check out Managed Magento hosting and avail Free Trial for 3 Days.

Conclusion

After the implementation of all the steps above, you should be able to override Model in Magento 2. You can override more Models with the same approach depending on your requirements. If you still have any confusion related to this tutorial, just leave a comment below!

Subscribe Newsletter

Subscribe to get latest Magento news

Experience Faster
Managed Magento Hosting