Magento 2 Product Status – Set Product Status Programmatically

magento2productstatus

I have idea we can set product status using following code in magento 1.x.but I’m not able to identify in magento 2.0 beta. i'm spending lot of time to search status.php file. i find following file.but no use.

magento2/app/code/Magento/Catalog/Model/Product/Attribute/Source/Status.php

$productid=10;// product id which you want to change status; 
    $storeid=1 
    Mage::getModel('catalog/product_status')->updateProductStatus($productid, $storeid, Mage_Catalog_Model_Product_Status::STATUS_ENABLED);

Best Answer

You'll want to use \Magento\Catalog\Api\ProductRepositoryInterface

Declare a dependency on it by adding it to your constructor

    public function __construct(
    \Magento\Catalog\Api\ProductRepositoryInterface $productRepository
) {
    $this->productRepository = $productRepository;
}

Then you can update the status and save it back with the following code in your method

    $product = $this->productRepository->getById($productId);
    $product->setStatus(\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED);
    $this->productRepository->save($product);
Related Topic