I am trying to load all variations of a product.
While using google I found this code snippet:
class ProductViewSubscriber implements EventSubscriberInterface
{
private EntityRepositoryInterface $productRepository;
public function __construct(EntityRepositoryInterface $productRepository)
{
$this->productRepository = $productRepository;
}
public function getVariantsOfProduct(SalesChannelProductEntity $product, Context $context): EntitySearchResult
{
$parentProduct = $product->getParent();
if ($parentProduct != null) {
// We need the parent product to find all variants
$product = $parentProduct;
}
$criteria = new Criteria();
$criteria->addFilter(new EqualsFilter('product.parentId',
$product->getUniqueIdentifier()));
return $this->productRepository->search($criteria, $context);
}
public static function getSubscribedEvents(): array
{
return [
ProductPageLoadedEvent::class => ['addVariants'],
];
}
public function addVariants(ProductPageLoadedEvent $pEvent)
{
$products = $this->getVariantsOfProduct($product = $pEvent->getPage()->getProduct(), $pEvent->getContext());
$matchingVariants = $products->getElements();
}
}
But using the code snippet only an empty list is returned, though there are definitely variants to that product. How can I fix this code?