Magento 1.9 – Update Custom Attribute Value via Script

custom-attributesmagento-1.9PHP

I'm trying to write a script that will be run by a cron that updates a custom attribute. The attribute is defined by a 3rd Party Module and has a value of "Blank, Yes or No" as a dropdown selection on the frontend. The corresponding values for the attribute in the table catalog_product_entity_int are 1 for Yes and 2 for No.

So far I have the following code. It separates out all the child products for each configurable product and it should assign them a value of "No" for the attribute.

<?php
include_once '../app/Mage.php';
Mage::app()->setCurrentStore( Mage_Core_Model_App::ADMIN_STORE_ID );

// Get all configurable and grouped products
$products = Mage::getModel('catalog/product')
    ->getCollection()
    ->addAttributeToSelect('name')
    ->addAttributeToFilter('type_id', array('in' => array('configurable', 'grouped')));

// Loop each configurable product
foreach ($products as $_product) {
    // testing single product only
    if ($_product->getId() == 981 ){



    // Get the child products for this product
    if ($_product->getTypeId() == 'configurable') {
        $simpleProducts = $_product->getTypeInstance(true)->getUsedProductIds($_product);
    } elseif ($_product->getTypeId() == 'grouped') {
        $simpleProducts = $_product->getTypeInstance(true)->getAssociatedProductIds($_product);
    }
    printf("Setting children of Product ID %s\r\n", $_product->getId());



    // Loop each child product
    foreach($simpleProducts as $_simpleID) {
        try {

            $_simple = Mage::getModel('catalog/product')->load($_simpleID);
            $attrCode = 'webpos_visible';
            $valueText = 2;
            $valueId = Mage::getModel('catalog/product')->getResource()->getAttribute($attrCode)->getSource()->getOptionId($valueText);
            $_simple->setData($attrCode, $valueId);

            printf("Product ID %s saved as 'Webpos Disabled'\r\n", $_simple->getId());

        } catch ( Exception $e ) {
            print_r($e);


           }
        }
    }
}

This script seems to run successfully but the attributes are not updated in the backend

Please help

Best Answer

Since you did define the attribute's option value already in $valueText (this is not the attribute's option id) you can save this information as below:

// Loop each child product
    foreach($simpleProducts as $_simpleID) {
        try {
            $valueText = 2;
            $_simple = Mage::getModel('catalog/product')->load($_simpleID);
            $_simple->setWebposVisible($valueText);
            // or
            // $attrCode = 'webpos_visible';
            // $_simple->setData($attrCode, $valueText);
            $_simple->save();

            printf("Product ID %s saved as 'Webpos Disabled'\r\n", $_simple->getId());

        } catch ( Exception $e ) {
            print_r($e);


           }
        }
    }
Related Topic