I know how I can add a product attribute from an installer script, but how do I tell Magento to use one of the values as default value? (or more values in case it's a multiselect attribute).
I use this code in an installer script to add an attribute with options:
$installer->addAttribute('catalog_product', "some_code_here", array(
'type' => 'int', //or varchar if it's multiselect
'input' => 'select', //or multiselect
'label' => 'Attribute label here',
'sort_order' => 1000,
'required' => false,
'global' => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_STORE,
'backend' => 'eav/entity_attribute_backend_array',
'option' => array (
'values' => array(
0 => 'Value 1',
1 => 'Value 2',
2 => 'Value 3',
)
),
));
So I need to make the Value 2
be the default value. Or Value 2
and Value 3
in case I create a multiselect attribute
Best Answer
tl;dr: For select attributes this cannot be declared directly in the initial
addAttribute()
call; two calls are required.In order to set the default value,
eav_attribute.default
must be set with the primary key value from theeav_attribute_option
table At a high level the need for two calls is apparent by looking at the flow and function of theaddAttribute()
andaddAttributeOption()
methods:eav_attribute
tableaddAttributeOption()
to insert/update option valuesThe only hope then would be that
addAttributeOption()
will be able to update theeav_attribute
record. However, there is no code which does this. The only tables accessed by this method areeav_attribute_option
andeav_attribute_option_value
.It is therefore necessary to call
getAttribute()
after the initialaddAttribute()
call, grab the attribute option ID and then callupdateAttribute()
.Edit:
After the earlier answer I couldn't help but verify my answer against the existing code; after all, for
catalog_product
entities we have a nice MVC flow to follow thanks to the attribute CRUD GUI. And there it was, in\Mage_Adminhtml_Catalog_Product_AttributeController::saveAction()
, that I saw the attribute model being set with the following data just before being saved:Note that the attribute's
default
value has references to thevalue
keys. Do a little digging and you end up at\Mage_Eav_Model_Resource_Entity_Attribute::_saveOption()
, which is called from this resource's_afterSave()
method - just as you'd expect given that we need to have aneav_attribute
record to update. You can even see how multiselect and select defaults are handled in the same place, just before the final update:So, another alternative is to work directly with the resource model.