Magento 1.8 – Set Default Option as ‘No’ for Custom Select Attribute

custom-attributesmagento-1.8option

I have used below code to generate a custom select attribute.

$installer->addAttribute('catalog_product', "best_seller_flag", array(
    'type'       => 'int',
    'group'      => 'Flags',
    'input'      => 'select',
    'label'      => 'Best seller flag',
    'default'    => '',
    'sort_order' => 2,
    'required'   => false,
    'global'     => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_STORE,
    'backend'    => 'eav/entity_attribute_backend_array',
    'option'     => array (
        'values' => array(
            0 => 'No',
            1 => 'Yes'
        )
    ),
));

$installer->addAttribute('catalog_product', /* another attribute */);

$installer->addAttribute('catalog_product', /* another attribute */);

The attribute was created successfully but by default "No" option is not selected. It is showing in admin panel as shown in the below image:

enter image description here


When I inspect the element, I can see the following code (related to a single attribute)

<select class=" select" name="product[best_seller_flag]" id="best_seller_flag">
    <option selected="selected" value=""></option>
    <option value="156">No</option>
    <option value="157">Yes</option>
</select>

As you can see in above code, the values of options are not 0 and 1, instead they are some numbers like 156 and 157.

I think this is the main reason to why the 'default' => '' is not working. (even tried 'default' => '0')

Please help

Best Answer

Using the boolean source model instead of the table source model you can easily define the default 0:

$installer->addAttribute('catalog_product', "best_seller_flag", array(
    'type'       => 'int',
    'group'      => 'Flags',
    'input'      => 'select',
    'label'      => 'Best seller flag',
    'default'    => '0',
    'sort_order' => 2,
    'required'   => false,
    'global'     => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_STORE,
    'source'     => 'eav/entity_attribute_source_boolean'
));
Related Topic