How to Mass Update Product Attribute Value Using Install Script

product-attribute

If we comment Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID); then its work fine, but product update not reflected.

 $installer = $this;
        try{
            $productTypes = array(
                Mage_Catalog_Model_Product_Type::TYPE_SIMPLE,
                Mage_Catalog_Model_Product_Type::TYPE_CONFIGURABLE
             );
            $productTypes = join(',', $productTypes);

            $installer->startSetup();
        $installer->addAttribute('catalog_product', 'discount', array(
            'group'             => 'Prices',
            'type'              => Varien_Db_Ddl_Table::TYPE_VARCHAR,
            'backend'           => '',
            'frontend'          => '',
            'label'             => 'Discount',
            'input'             => 'price',
            'class'             => '',
            'source'            => '',
            'global'            => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_STORE,
            'visible'           => true,
            'required'          => false,
            'user_defined'      => true,
            'default'           => '',
            'searchable'        => false,
            'filterable'        => true,
            'comparable'        => false,
            //'visible_on_front'  => true,
            'unique'            => false,
            'apply_to'          => $productTypes,
            'is_configurable'   => false
        ));

      Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
      $products = Mage::getModel("catalog/product")->getCollection()->addAttributeToSelect('*');

     foreach($products as $_product) {
            $product = Mage::getModel('catalog/product')->load($_product->getId());

          if($product->getFinalPrice() < $product->getPrice()){

            $diffAmt = $product->getPrice() - $product->getFinalPrice();
            $discountPer = ($diffAmt/ $product->getPrice()) * 100;
            $product->setDiscount($discountPer);
            $product->save();
          }
     }

        $installer->endSetup();
        }
        catch(Exception $ex){
            echo $ex->getMessage();
        }

Best Answer

Mage::getSingleton('catalog/product_action')->updateAttributes($array_product, array('attribute_code' => "something pretty"), 0);

$array_product => array of product ids, which could be easily fetched

using Mage::getModel("catalog/product")->getCollection()->getAllIds()

attribute_code => is your attribute code

something pretty => your attribute value

0 is store id replace with your store id

Related Topic