5

For a custom indexer, I need to load a product collection with the attribute values for a given store, while not in a store context.

As it has been established in Magento 2: How to Filter a Product Collection By Store ID, ProductRepository::getList() does not have a store id parameter and also does not understand store_id as filter in the SearchCriteria parameter.

In the comments above, @IgorMinyaylo explains that in the REST APIs it is done by the store id URL part:

http://<magento_host>/rest/<store_code>/

So I looked how the Webapi module processes this part and found:

/**
 * Process path info
 *
 * @param string $pathInfo
 * @return string
 * @throws NoSuchEntityException
 */
public function process($pathInfo)
{
    $pathParts = $this->stripPathBeforeStorecode($pathInfo);
    $storeCode = $pathParts[0];
    $stores = $this->storeManager->getStores(false, true);
    if (isset($stores[$storeCode])) {
        $this->storeManager->setCurrentStore($storeCode);
        $path = '/' . (isset($pathParts[1]) ? $pathParts[1] : '');
    } else if ($storeCode === self::ALL_STORE_CODE) {
        $this->storeManager->setCurrentStore(\Magento\Store\Model\Store::ADMIN_CODE);
        $path = '/' . (isset($pathParts[1]) ? $pathParts[1] : '');
    } else {
        $path = '/' . implode('/', $pathParts);
    }
    return $path;
}

The relevant line is:

        $this->storeManager->setCurrentStore($storeCode);

But this sets the "current store" as global state. This is fine for an API request, but I would rather avoid it when I'm actually in admin or cron context. The risk of undesired side effects is too high.

I also looked at the core indexers but those operate on a level of implementation detail which would not be a good fit for an extension.


So how can I achieve the same without $storeManager->setCurrentStore()? Do I have to construct my collection manually instead of using the repository? Can I use store emulation?

In Magento 2: Can you Filter By store_id Using a Product Repository a plugin for the product collection is proposed as fix, which makes it possible to add store_id as SearchCriteria parameter. It's good enough as a workaround, but does not seem "right" to me.

0

Your Answer

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