1

I'm trying to update products programmatically but I got only first product from array updated. All of products in array have status "2" (disabled) in DB. I'm using $this->productRepositoryInterface - it's \Magento\Catalog\Api\ProductRepositoryInterface

$productSkus = ['A1', 'A2', 'A3'];

foreach ($productSkus as $sku) {
    $productToSave = $this->productRepositoryInterface->get($sku);
    echo "Product {$productToSave->getId()} is loaded and ready to update".PHP_EOL;
    $productToSave->setStatus(1);
    $this->productRepositoryInterface->save($productToSave);
}

After that code executed - I got only A1 set to "Enabled". Other products keeping be disabled. Echo says it's loading everytime new product to be updated. Magento 2.2.4 EE (CE is also affected)

1

Try to use this below code :

protected $_productCollectionFactory;
protected $_product;

 public function __construct(
    .................
    \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,
    \Magento\Catalog\Model\Product $product,
    .................
)
{
    .................    
    $this->_productCollectionFactory = $productCollectionFactory;
    $this->_product = $product;
    .................
}

public function yourFunction()
{
    $collection = $this->_productCollectionFactory->create()->getCollection();
    foreach ($collection as $value) {
        $product = $this->_product->load($value->getId());
        $product->setStatus(1);
        $product->save();
    }
}

Remove var and generated folder.

| improve this answer | |
0

First we need to get productCollection with all products. Then you run a loop for every product and check a condition. This condition should decide if you need to activate or deactivate a product. This can be anything, I used a active product attribute.

$productIdsActivate = [];
$productIdsDeactivate = [];

foreach($this->productCollection as $product)
{
    ...
    if($product->getActivate()) {
        $productIdsActivate[] = $product->getId();
    } else {
        $productIdsDeactivate[] = $product->getId();
    }
}

$storeIds = array_keys($this->storeManager->getStores());

//activate products
$updateAttributes['status'] = \Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED;
foreach ($storeIds as $storeId) {
    $this->productAction->updateAttributes($productIdsActivate, $updateAttributes, $storeId);
}

For more reference click here

I hope it will help you.

| improve this answer | |
  • But how to i can write my SKU number is this code ? In this $productIdsActivate = []; – Wajahat Bashir Oct 9 '19 at 8:50

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.