0

I would like to add a new function to Product Model which be accessible each time I create Product.

Below, my code :

src/app/code/Project/Catalog/Model/Product.php :

<?php

namespace Project\Catalog\Model;

class Product extends \Magento\Catalog\Model\Product
{
    public function newFunction()
    {
     // myfunction
    }
}

src/app/code/Project/Catalog/etc/di.xml :

<?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\Catalog\Api\Data\ProductInterface" type="Project\Catalog\Model\Product" />
</config>

src/app/code/Project/Catalog/Block/Block.php

<?php

namespace Project\Catalog\Block;

use Magento\Backend\Block\Template;

class Block extends Template
{
    public function newFunction()
    {
        return $this->_currentProduct->newFunction();
    }
}

But I got the following exception :

Exception #0 (Magento\Framework\Exception\LocalizedException): Invalid method Magento\Catalog\Model\Product\Interceptor::newFunction

Why my new function is not find ? Where am I wrong ?

  • can't find the method isProductNew in your code – fmsthird Mar 20 at 10:18
  • Sorry, bad copy/paste : it's not isProductNew, it's newFunction – Kozame Mar 20 at 10:20
  • did you run compile? – fmsthird Mar 20 at 10:22
1

Can you do the below change in your di.xml file and confirm.

<?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\Catalog\Model\Product" type="Project\Catalog\Model\Product" />
</config>
  • You're right, that work ! But how can I override the public function __construct() of Magento\Catalog\Model\Product ? I need to add something in, but when I try to call parrent::__construct, I don't know what I need to put in param.. – Kozame Mar 20 at 10:27
  • You can create type node di.xml file to supply additional arguments to the class without disturbing the construct function. May i know the reason why you want to change the construct() function ? – Thamo Mar 21 at 10:12

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.