1

I tried to add custom data to the endpoint V1/categories but ended up with getting error

My code is below

  1. etc/extension_attributes.xml
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Api/etc/extension_attributes.xsd">
    <extension_attributes for="Magento\Catalog\Api\CategoryRepositoryInterface">
        <attribute code="banner_slider" type="string" />
    </extension_attributes>
</config>

2.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">
    <type name="Magento\Catalog\Api\CategoryRepositoryInterface">
        <plugin name="banner_image_data" type="Vendor\ModuleName\Plugin\Model\CategoryRepository"/>
    </type>
</config>

3.Plugin

use Magento\Catalog\Model\CategoryRepository as Subject;

class CategoryRepository
{

    /**
     * @param Subject $subject
     * @param CategoryInterface $data
     * @return CategoryInterface
     */
    public function afterGet(
        Subject $subject,
        CategoryInterface $data
    )
    {
        $extensionAttributes = $data->getExtensionAttributes();
        $extensionAttributes->setBannerSlider('sandesh');
        $data->setExtensionAttributes($extensionAttributes);
        return $data;
    }
}

My error

 Call to undefined method Magento\Catalog\Api\Data\CategoryExtension::setBannerSlider()

1 Answer 1

1

Please replace your files with the following code:

1.etc/extension_attributes.xml

<extension_attributes for="Magento\Catalog\Api\Data\CategoryInterface">
        <attribute code="banner_slider" type="string" />
    </extension_attributes>

2.di.xml

<type name="Magento\Catalog\Api\CategoryRepositoryInterface">
        <plugin name="banner_image_data" type="Vendor\ModuleName\Plugin\Model\CategoryRepository"/>
    </type>

3.Plugin

<?php
namespace Vendor\ModuleName\Plugin\Model;
use Magento\Catalog\Api\CategoryRepositoryInterface as Subject;

class CategoryRepository
{

    /**
     * @param Subject $subject
     * @param CategoryInterface $data
     * @return CategoryInterface
     */
    public function afterGet(
        Subject $subject,
        \Magento\Catalog\Api\Data\CategoryInterface $data
    )
    {
        $extensionAttributes = $data->getExtensionAttributes();
        $extensionAttributes->setBannerSlider('sandesh');
        $data->setExtensionAttributes($extensionAttributes);
        return $data;
    }
}
?>

let me know if you need any further assistanse. don't forget to upvote and mark as answer :)

1
  • Thank you @Joao71 answer worked
    – sandesh s
    Commented Jul 9, 2020 at 6:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.