Search code examples
phpmagento

Magento - module is not updating prices on a per-website basis


I am having trouble with a module that is supposed to update prices on a per-website basis.

At the top of my module I have :

Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);

This should mean that when I call the module (the module has a frontend) I am able to update prices etc as 'admin'. However, this just isn't happening. Currently I have gone on a few desperate efforts to get it working - seeing if number formats trip it up or indexes not reindexed, cache problems and anything else.

The following snippet actually produces the right numbers but it just is not saving to the database. Any ideas?

$product = Mage::getModel('catalog/product')->
           setStoreId($storeId)->setWebsiteId($websites[$store])->
           loadByAttribute('sku',$price['SKU']);
$oldprice=(float)str_replace(",","",$product->getPrice());

if($newprice!=$oldprice) {
    Mage::log($product->getPrice());
    $product->setPrice(number_format($newprice,4,".",""));
    Mage::log($product->getPrice());
    $product->getResource()->saveAttribute($product, 'price');
    $product->save();
    Mage::log($product->getPrice());
    unset($product);
}

Solution

  • Let's assume that you are updating the prices of products using a method in your module's class, with the following sample code:-

    public function updateProductPrices ($sku, $newPrice) {
        Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
    
        $websites = Mage::app()->getWebsites();
    
        $product = Mage::getModel('catalog/product')
        $productId = $product->getIdBySku($sku);
    
        foreach ($websites as $_eachWebsite) {
            $_websiteId = $_eachWebsite->getWebsiteId();
    
            $websiteObj = new Mage_Core_Model_Website();
            $websiteObj->load($_websiteId);
    
            $storeIds = $websiteObj->getStoreIds();
    
            if (count($storeIds)) {
                foreach ($storeIds as $_eachStoreId) {
                    $product->setStoreId($_eachStoreId)
                            ->load($productId);
    
                    $oldPrice = $product->getPrice();
    
                    if ($oldPrice != $newPrice) {
                        $product->setPrice($newPrice);
                        $product->save();
                    }
                }
            }
    
            unset($storeIds, $websiteObj, $_websiteId);
        }
    
        unset($product);
    }
    

    Hope it helps.