0

I have created a custom attribute which allows me to disable products that have past a specified date. First I fetch the collection (getCollection), filter by those with an end date and with status 'enabled' and then save it in $toBeZeroedCollection. Then:

$toBeZeroedIds = $toBeZeroedCollection->getAllIds();
    unset($toBeZeroedCollection);
    if ($toBeZeroedIds) {
        Mage::getSingleton('catalog/product_action')->updateAttributes(
                     $toBeZeroedIds,
                     array('status' => Mage_Catalog_Model_Product_Status::STATUS_DISABLED),
                     Mage_Core_Model_App::ADMIN_STORE_ID
            );

The above code disables the product. But I want to also set the quantity to zero and stock availability to 'Out of Stock'. Do you know how I can achieve this?

I tried variations of the following but have had no success, even the disabled action no longer works with these variations.

Mage::getSingleton('catalog/product_action')
->updateAttributes(
                     $toBeZeroedIds,
                     array('status' => Mage_Catalog_Model_Product_Status::STATUS_DISABLED, 
                    'is_in_stock' => Mage_CatalogInventory_Model_Stock_Status::STATUS_OUT_OF_STOCK, 
                    'qty' => 0),
                     Mage_Core_Model_App::ADMIN_STORE_ID
            );

Update

I got this working using product ids, with code similar to Parassood's below.

foreach($toBeZeroedIds as $productId){

        $stockItem = Mage::getModel('cataloginventory/stock_item')->loadByProduct($productId);
        $stockItem->setData('qty', 0);
        $stockItem->save();


    }

I also had to lengthen my cron settings as per https://stackoverflow.com/a/21202940/3779933

1 Answer 1

2

You could loop through the $zeroCollection and do something like:

foreach($zeroCollection as $product){

  $stockItem = $product->getStockItem();
  $stockItem->setIsInStock(false)
            ->setQty(0)
            ->save();

} 
2
  • Thanks for the suggestion. When I use this, it doesn't affect the stock or quantity of the products. Also the disable function in my code stops working too. Do you know what else I could try? For example is there a way to set stock status and quantity using the product id?
    – MW Millar
    Commented Mar 20, 2015 at 11:41
  • As commented in my edit, your code wasn't the fix I needed, but it helped me find the solution. Thanks
    – MW Millar
    Commented Mar 20, 2015 at 17:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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