I have a custom attribute for my products called 'car_model'. This is a multi-value field. Now I try to create a synchronization script to synchronize this data between Magento and another system. I start off with getting all products:
ini_set('display_errors',1);
require('app/Mage.php');
umask(0);
Mage::app();
$collection = Mage::getModel('catalog/product')->getCollection();
//fetch name and orig_price into data
$collection->addAttributeToSelect('name');
$collection->addAttributeToSelect('car_model');
$products = array();
foreach ($collection as $product) {
$product = Mage::getModel('catalog/product')->load($product->getId());
$product_id = $product->getId();
$sku = $product->getSku();
$product_name = $product->getData('name');
$model = $product->getAttributeText('car_model');
$products[$sku] = array('product_id'=>$product_id, 'model' => $model, 'modified' => false, 'product' => $product);
}
The $model variable contains the correct (text) values, so no problem there.
Then I do some hocus pocus to get what needs to be updated which resulted in the following code to save the products:
foreach($products as $sku=>$product) {
if($product['modified']) {
$attr = $product['product']->getResource()->getAttribute('car_model');
//$models = array();
foreach($product['model'] as $m) {
$option_id = $attr->getSource()->getOptionId($m);
//$models[$option_id] = $m;
$product['product']->setData('car_model', $option_id);
// $product['product']->addAttributeUpdate('car_model', $option_id);
}
try {
//$product['product']->setData('car_model', $models);
//$product['product']->addAttributeUpdate('car_model', $option_id);
//$product['product']->save();
$product['product']->getResource()->saveAttribute($product['product'], 'car_model');
echo "Set product " . $product['product_id'] . " " . $sku . " to " . implode(",",$product['model']) . "<br>";
} catch(Exception $e) {
echo 'failed updating product ' . $product['product_id'] . ' with message: ' . $e->getMessage() . '<br>';
}
}
}
As you can see from the commented lines I tried many different things, but it doesn't want to save the attributes correctly. From what I understand I need to call setData('car_model', $option_id) multiple times for all values. When I retrieve the product after saving though, I only get one value returned.
Furthermore, when I go to the backend, the values are not selected. I tried reindexing and clearing the cache (also emptying var/cache), but this doesn't make any difference. It seems like a basic thing to do, but somehow I don't get it to work. Any thoughts?
Best Answer
I believe the following should be sufficient:
$product->setData('car_model', $array_of_values)->save();
Although, if it's a standalone script, it won't allow you to save products unless you trick it into thinking you're in the backend by adding this at the top of your file:
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);