Question

I am trying to emulate the same behavior as when you use the admin panel to disable a product. I am trying to do something like this:

$product = $this->productRepository->get($sku);
$product->setStatus(\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_DISABLED);
$this->productRepository->save($product);

But I still see it as enabled in the admin panel.

Thanks.

Was it helpful?

Solution

The problem was that $product = $this->productRepository->get($sku); gets a product for the default store. And if you want to disable it globally you need to pass

$this->productRepository->get(
    $sku,
    true/* edit mode */,
    0/* global store*/,
    true/* force reload*/
);

OTHER TIPS

You can try with below code,

You can check core file code, vendor/magento/module-catalog-sample-data/Model/Product.php

class Product
{
    public function __construct(
        \Magento\Catalog\Model\ProductFactory $productFactory
    ) {
        $this->productFactory = $productFactory;
    }
    public function saveproduct()
    {

        $product = $this->productFactory->create();
        $product->setStatus(\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_DISABLED);
        $product->save();
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top