2

I need to get the product collection with all extension attributes, specifically I need then to get the stockItem object with $product->getExtensionAttributes()->getStockItem(). So I have created a function like this:

protected function getCollection(ProductInterface $product): Collection
{
    $collection = $this->productCollectionFactory->create();

    $collection
        ->addAttributeToSelect('*')
        ->addAttributeToFilter('visibility', ['eq' => Visibility::VISIBILITY_BOTH])
        ->addAttributeToFilter('status', ['eq' => Status::STATUS_ENABLED])
        ->addFieldToFilter('entity_id', ['neq' => $product->getId()])
        ->setPageSize(5);

    return $collection;
}

then I get all items from collection with $collection->getItems(), but in the loop of getItems() the extension attributes are null, why and how can I get them?

protected function populateProductList(Collection $collection)
{
    $items = $collection->getItems();

    $products = array_map(function ($product): ProductInterface {
        $stockItem = $product->getExtensionAttributes()->getStockItem();
        var_dump($stockItem);die; // IS NULL

        return $product;
    }, $items);

    return $products;
}

If I get a Product from the get method of productRepository, that product has all extension attributes compiled, I don't want to use productRepository to get another time the products for "only" the extension attributes, I want to avoid another call for performance reasons.

0

Try using getData to get complete object Data

protected function populateProductList(Collection $collection)
{
    $items = $collection->getItems();

    $products = array_map(function ($product): ProductInterface {
        $stockItem = $product->getExtensionAttributes()->getStockItem()->getData();
        var_dump($stockItem);die; // IS NULL

        return $product;
    }, $items);

    return $products;
}
  • 1
    It doesn't work because getStockItem() is null – Mirko Rapisarda Apr 17 '19 at 6:36

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.