Pergunta

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 ?

Foi útil?

Solução

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>
Licenciado em: CC-BY-SA com atribuição
Não afiliado a magento.stackexchange
scroll top