mfisher86
mfisher86

Reputation: 75

Magento adding new options to a drop down attribute

Hello Im currently writing a product syncronisation script for magento. I know how to add a new product with a given attribute set. However one of the atributes i am using is a size field. When a new size is encounterd I want to add this option to the attribute, I am wondering how to do this please?

Upvotes: 4

Views: 7963

Answers (3)

Łukasz Linczewski
Łukasz Linczewski

Reputation: 51

Here is a script to add new option to attribute from Product View or Block:

$attributeInfo = Mage::getResourceModel('eav/entity_attribute_collection')
 ->setCodeFilter(YOUR_ATTRIBUTE_CODE)
 ->getFirstItem();

$options = $attributeInfo->getSource()->getAllOptions(false);
$_optionArr = array(
     'value'  => array(), 
     'order'  => array(), 
     'delete' => array()
);
foreach ($options as $option) {
    $_optionArr['value'][$option['value']] = array($option['label']);
}
$_optionArr['value']['option_1'] = array(NAME_OF_OUR_NEW_OPTION);
$attribute->setOption($_optionArr);
$attribute->save();

...

Upvotes: 5

Kus
Kus

Reputation: 2537

Put a file ie: test-attribute.php in your Magento root.

<?php
// Include and start Magento
require_once dirname(__FILE__).'/app/Mage.php';
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
// Load attribute model and load attribute by attribute code
$model = Mage::getModel('catalog/resource_eav_attribute')->load('some_dropdown_attribute', 'attribute_code');
// Get existing options
$options = $model->getSource()->getAllOptions(false);
// Get the count to start at
$count = count($options) + 1;
// Prepare array
$data = array(
    'option' => array(
        'value' => array(),
        'order' => array()
    )
);
// You can loop here and increment $count for multiple options
$key = 'option_'.$count;
$data['option']['value'][$key] = array('Test '.$count);
$data['option']['order'][$key] = 0;
// Add array to save
$model->addData($data);
// Save
$model->save();

Should create a new option called Test X on the attribute. Tested on Magento Enterprise 1.11.2

Upvotes: 4

mfisher86
mfisher86

Reputation: 75

After doing some more looking around I finaly found out how to do it. Then I found a extension to xml-api that extends api to support operations such as one i wanted to do.

The extension i used was MagentoeXtended

Upvotes: -2

Related Questions