Skip to content

ProductRepository::save assigns the product to all websites #8520

@dunarri

Description

@dunarri

Preconditions

Magento CE v2.1.1
at least 2 stores and websites
a product to test that is only in 1 of the websites

Steps to reproduce

  1. Create a module with an observer on catalog_product_save_after
  2. Trigger this code by saving any product in the admin
  3. sample observer code that causes the problem:
    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        $product = $observer->getProduct();
        if ($product->getSku() != 'TEST-SKU') {
            $product = $this->productRepository->get('TEST-SKU');
            $product->setPrice(9.99);    // or anything you want to change to test
            $this->productRepository->save($product);
        }
    }
  1. now observe this product you modified, it will have been added to all websites

Expected result

The products websites should remain unchanged.
This is the behavior when saving a product through the admin, but it is because the Save controller uses the old deprecated $product->save() method.

Actual result

The product has been added to all websites.
This is due to the assignProductToWebsites method of ProductRepository:

    if ($this->storeManager->getStore()->getCode() == \Magento\Store\Model\Store::ADMIN_CODE) {
        $websiteIds = array_keys($this->storeManager->getWebsites());

Metadata

Metadata

Assignees

Labels

Fixed in 2.2.xThe issue has been fixed in 2.2 release lineIssue: Clear DescriptionGate 2 Passed. Manual verification of the issue description passedIssue: ConfirmedGate 3 Passed. Manual verification of the issue completed. Issue is confirmedIssue: Format is validGate 1 Passed. Automatic verification of issue format passedIssue: Ready for WorkGate 4. Acknowledged. Issue is added to backlog and ready for developmentReproduced on 2.2.xThe issue has been reproduced on latest 2.2 releaseReproduced on 2.3.xThe issue has been reproduced on latest 2.3 releasenon-issue

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions