Magento – update product programmatically magento 2

csvmagento2productscript

Whats wrong in my following code ? I am using a script to insert and update product details using csv. Products are inserting / updating without any issues. But only after updated a product…

I changed the status to Enabled. When I change it, The status changed and I am able to see the changes on edit page. But in the product grid, still It says, Disabled. Also the product is not displaying on front-end.

I cleared the cache and reindexed it. Here is my code.

$product_name = 'test product';
$sku = 'abc-123';
// if existing product update it, else insert the product
if ($productModel->getIdBySku($sku)) {
    $product = $productRepository->get($sku);
    array_push($arrUpdatedProducts, $sku);
    $product->setData('is_new_product', 5);
} else {
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); // instance of object manager
    $product = $objectManager->create('\Magento\Catalog\Model\Product');
    $product->setSku($sku); // Set your sku here
    $product->setName($product_name); // Name of Product
    $product->setAttributeSetId(4); // Attribute set id
    //$product->setStatus(1); // Status on product enabled/ disabled 1/0
    $product->setStatus(\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_DISABLED);
    $product->setTypeId(\Magento\Catalog\Model\Product\Type::TYPE_SIMPLE);
    $product->setVisibility(4); //Catalog, Search // visibilty of product (catalog / search / catalog, search / Not visible individually)
    $product->setTaxClassId(0); // Tax class id
    $product->setTypeId('simple'); // type of product (simple/virtual/downloadable/configurable)
    $product->setPrice(0);
    $product->setWebsiteIds(array(1));
    $product->setData('is_new_product', 4); // Yes
    $product->setStockData(
        array(
            'use_config_manage_stock' => 0,
            'manage_stock' => 1,
            'is_in_stock' => 1,
            'qty' => 11
        )
    );
}
$product->save();

$indexer = $this->indexerFactory->create();
$indexerCollection = $this->indexerCollectionFactory->create();
$ids = $indexerCollection->getAllIds();
foreach ($ids as $id){
    $idx = $indexer->load($id);
    if ($idx->getStatus() != 'valid'){
        $idx->reindexRow($id);
    }
}

Best Answer

I have experienced similar issues. The cause was that the ProductRepositories returns a product model with store_id > 0. If you save data then, it's only saved for the specified store view, but not for the default scope. My solution would be to add after

$product = $productRepository->get($sku);

the following line:

$product->setStoreId(0);

And, please, don't use the object manager, but a ProductFactory for creating a new product model.