9

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.

  • This code should work. What is the status when you look in the admin panel, the product details? Make sure the reindex mode is "on save" if you want to see the changes immediately – Stijn Duynslaeger - Echron Dec 29 '16 at 1:27
  • If I go to products > catalog it still says enabled. And If I try to [GET] /products/search/?searchCriteria... I still see it and the status is equal to 1. – awavi Dec 29 '16 at 1:33
  • You are sure this code gets executed? Can you debug the code? Maybe try to set another property like description to see if the product gets saved. Check the error logs. I once was unable to save a product because of an invalid field... (you can check that by trying to save a change in the admin panel) – Stijn Duynslaeger - Echron Dec 29 '16 at 1:36
  • Yes I am sure it gets executed. I can and have debugged it. No logs. And no, it does not work. – awavi Dec 29 '16 at 1:52
  • You mean you can't save the product in the admin panel? – Stijn Duynslaeger - Echron Dec 29 '16 at 2:07
11

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*/
);
| improve this answer | |
  • Please explain how to use this code to disable the product globally? – Purushotam Sharma Feb 10 '18 at 8:48
  • This code does! – awavi Feb 10 '18 at 12:27
  • thank you - it worked for me! – Oktarin Jul 2 '19 at 17:05
1

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();
    }
}
| improve this answer | |
  • But this one is when you are creating a new product. I now know what the problem is. I am saving the product just within the scope of the current store. But globally it will still be enabled. – awavi Dec 29 '16 at 14:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.