How to Add Attribute Option Value Programmatically in Magento

1
47
views
Here, I am explaining about how to add attribute option value programmatically in magento. you can also add the attribute option value from the admin panel of the magento but if there are so many attribute option value then it takes so much time to add from the admin so you can add attribute option value programmatically in magento. You just need to create filename.txt file with attribute options Which is separated by enter(Each single option in separate line). And create importattributeoptions.php file add put below code in it. And Replace the ATTRIBUTE_CODE with your attribute code.

<?php

require_once ‘app/Mage.php’;$app = Mage::app(‘admin’);umask(0);
$myFile = “filename.txt”; // File in which attribute option values are there.
$f = fopen($myFile, “r”);
$myValue = array();
while($line = fgets($f, filesize($myFile)))
{
array_push($myValue,$line);
}

for($i=0;$i<count($myValue);$i++)
{
$attribute_model        = Mage::getModel(‘eav/entity_attribute’);

$attribute_code         = $attribute_model->getIdByCode(‘catalog_product’, ‘ATTRIBUTE_CODE‘);
$attribute              = $attribute_model->load($attribute_code);

if(!attributeValueExists(‘ATTRIBUTE_CODE‘, $myValue[$i]))
{
$value[‘option’] = array($myValue[$i]);
$order[‘option’] = $i;
$result = array(‘value’ => $value,’order’ => $order);
$attribute->setData(‘option’,$result);
$attribute->save();
}
}

function attributeValueExists($arg_attribute, $arg_value)
{
$attribute_model        = Mage::getModel(‘eav/entity_attribute’);
$attribute_options_model= Mage::getModel(‘eav/entity_attribute_source_table’) ;

$attribute_code         = $attribute_model->getIdByCode(‘catalog_product’, $arg_attribute);
$attribute              = $attribute_model->load($attribute_code);

$attribute_table        = $attribute_options_model->setAttribute($attribute);
$options                = $attribute_options_model->getAllOptions(false);

foreach($options as $option)
{
if ($option[‘label’] == $arg_value)
{
return $option[‘value’];
}
}
return false;
}

Advertisement

?>


Thanks for reading my blog. I hope it will help you, Please leave your comments here if it’s really help you. 🙂 

Thank You :),
Mayank Zalavadia