Upgrade Script – Create New Select Attribute with Options in Magento 1

attributesmagento-1product

I would like to create a new product attribute with some predefined options using an upgrade script.

I have an upgrade script working, so the only thing i dont know how to do is to add the drop down options along with the attribute.

I am adding my attribute inside my modules upgrade script using the following:

$installer->addAttribute('catalog_product', "shirt_size", array(
    'type'       => 'int',
    'input'      => 'select',
    'label'      => 'Shirt Size',
    'sort_order' => 1000,
    'required'   => false,
    'global'     => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_STORE,
));

How can I add 3 options along with it: small, medium and large?

I do not want to use a custom source model. I want normal options

Best Answer

This is a classic case where code-generation is your friend. Stop creating these by hand, and try using the following free and open source script, (which has also been incorporated into the n98-magerun tool)

For example, the following will duplicate the sample data's color attribute

$ magento-create-setup.php color
//WARNING, non false value detected in is_used_for_price_rules.  The setup resource migration scripts may not support this (per 1.7.0.1)
<?php
if(! ($this instanceof Mage_Catalog_Model_Resource_Setup) )
{
    throw new Exception("Resource Class needs to inherit from " .
    "Mage_Catalog_Model_Resource_Setup for this to work");
}

$attr = array (
  'attribute_model' => NULL,
  'backend' => '',
  'type' => 'int',
  'table' => '',
  'frontend' => '',
  'input' => 'select',
  'label' => 'Color',
  'frontend_class' => '',
  'source' => '',
  'required' => '0',
  'user_defined' => '1',
  'default' => '',
  'unique' => '0',
  'note' => '',
  'input_renderer' => NULL,
  'global' => '1',
  'visible' => '1',
  'searchable' => '1',
  'filterable' => '1',
  'comparable' => '1',
  'visible_on_front' => '0',
  'is_html_allowed_on_front' => '0',
  'is_used_for_price_rules' => '1',
  'filterable_in_search' => '1',
  'used_in_product_listing' => '0',
  'used_for_sort_by' => '0',
  'is_configurable' => '1',
  'apply_to' => 'simple',
  'visible_in_advanced_search' => '1',
  'position' => '1',
  'wysiwyg_enabled' => '0',
  'used_for_promo_rules' => '1',
  'option' => 
  array (
    'values' => 
    array (
      0 => 'Green',
      1 => 'Silver',
      2 => 'Black',
      3 => 'Blue',
      4 => 'Red',
      5 => 'Pink',
      6 => 'Magenta',
      7 => 'Brown',
      8 => 'White',
      9 => 'Gray',
    ),
  ),
);
$this->addAttribute(Mage_Catalog_Model_Product::ENTITY, 'color', $attr);

If you're using the n98-magerun version, that'd be

$ n98-magerun dev:setup:script:attribute catalog_product color

Using code generation will let you get your job done quicker, and as time goes on you'll start to learn the format.

Related Topic