Search code examples
pluginsshopware6

Shopware 6 Plugin - Load and display ProductStream via id


I want to load ProductStream data via a given id and display it in the frontend, for example below the product cart. The ProductStream is not linked to a ProductCrossSelling and therefore not linked to a product.

I loaded a ProductStream Collection via the repository.

$criteria = new Criteria($producStreamIds);
$productStreamResult = $this->productStreamRepository->search($criteria, $context);
$productStreams = $productStreamResult->getEntities();

Now I need the associated list of products, to include them via cms-element-product-slider.html.twig.

I found a post with a similar question: How to get products from the product stream ID in Shopware 6?

The answer was, to use the function loadByStream of Core\Content\Product\SalesChannel\CrossSelling\ProductCrossSellingRoute.php, but this function is private.

The only public function is load and it needs a $productId as a parameter, which I do not have, because my ProductStream is not linked to a product.

Is there a clean way to load products of a ProductStream that is not linked to a ProductCrossSelling?

I have currently copied the code of the loadByStream function to load the products for the stream.

Or is there an other function in the shopware core that I can use for this case. I haven't found anything else.

It feels as if the current assumption is that ProductStreams are not used without connection to a ProductCrossSelling and thus to a product.


Solution

  • A product stream is really just a collection of criterium filters. You inject ProductStreamBuilder and call buildFilters with the id of your product stream to retrieve the filters. Then you use the filters as normal with your criteria, add a limit, sorting etc and fetch your product entities.

    // <argument type="service" id="Shopware\Core\Content\ProductStream\Service\ProductStreamBuilder"/>
    private ProductStreamBuilderInterface $productStreamBuilder;
    
    // <argument type="service" id="sales_channel.product.repository"/>
    private SalesChannelRepositoryInterface $productRepository;
    
    // ..
    
    $filters = $this->productStreamBuilder->buildFilters(
        $productStreamId,
        $salesChannelContext->getContext()
    );
    
    $criteria = new Criteria();
    $criteria->addFilter(...$filters);
    
    $products = $this->productRepository
        ->search($criteria, $salesChannelContext)
        ->getEntities();