I want to add extra data in product list rest api using extension attribute via Plugin in Magento 2 but it's not working.
> Uncaught TypeError: Argument 2 passed to
> Vendor\ModuleName\Plugin\ProductPlugin::afterGetList() must be an
> instance of Magento\Catalog\Api\Data\ProductSearchResultsInterface,
> instance of Magento\Framework\Api\SearchResults given
extension_attribute.xml
<extension_attributes for="Magento\Catalog\Api\Data\ProductInterface">
<attribute code="seller" type="Magento\Catalog\Api\Data\CustomOptionInterface[]" />
</extension_attributes>
di.xml
<type name="Magento\Catalog\Api\ProductRepositoryInterface">
<plugin name="add_more_info_in_product" type="Vendor\ModuleName\Plugin\ProductPlugin" sortOrder="15" />
</type>
Vendor\ModuleName\Plugin\ProductPlugin.php
use Magento\Catalog\Api\Data\ProductInterface;
class ProductPlugin
{
protected $productExtensionFactory;
protected $productFactory;
public function __construct(
\Magento\Catalog\Api\Data\ProductExtensionFactory $productExtensionFactory,
\Magento\Catalog\Model\ProductFactory $productFactory
)
{
$this->productFactory = $productFactory;
$this->productExtensionFactory = $productExtensionFactory;
}
public function afterGet(
\Magento\Catalog\Api\ProductRepositoryInterface $subject,
\Magento\Catalog\Api\Data\ProductInterface $entity
)
{
/** @var ProductInterface $product */
$product = $entity;
// Fetch the raw product model (I have not found a better way), and set the data onto our attribute.
//$productModel = $this->productFactory->create()->load($product->getId());
$extensionAttributes = $product->getExtensionAttributes(); /** get current extension attributes from product **/
$seller = [
'id' => (int) 10,
'name' => 'seller name',
'image' => null
];
$extensionAttributes->setSeller($seller);
$product->setExtensionAttributes($extensionAttributes);
return $product;
}
public function afterGetList(
\Magento\Catalog\Api\ProductRepositoryInterface $subject,
\Magento\Catalog\Api\Data\ProductSearchResultsInterface $searchCriteria
) : \Magento\Catalog\Api\Data\ProductSearchResultsInterface
{
$products = [];
foreach ($searchCriteria->getItems() as $entity) {
/** @var ProductInterface $product */
// Fetch the raw product model (I have not found a better way), and set the data onto our attribute.
//$productModel = $this->productFactory->create()->load($product->getId());
$extensionAttributes = $entity->getExtensionAttributes(); /** get current extension attributes from product **/
$seller = [
'id' => (int) 10,
'name' => 'seller name',
'image' => null
];
$extensionAttributes->setSeller($seller);
$entity->setExtensionAttributes($extensionAttributes);
$products[] = $entity;
}
$searchCriteria->setItems($products);
return $searchCriteria;
}
}
But the result for product list is null:
{
"status_code": 200,
"reason_phrase": "OK",
"body": null
}
So any suggestion about that please?