How to create custom attribute source type?

How to create custom attribute source type?

Have you ever need to create custom attribute source type? This is small example which will help you to create custom source type. I hope that it will be helpful.

Let’s go….
First of all you need to create sql setup file which will add attribute to your system with custom source type. Source type is defined in array : ‘source’ => ‘sourcetype/attribute_source_type’.

startSetup();
 
$installer->addAttribute('catalog_product', 'product_type', array(
        'group'             => 'Product Options',
		'label'             => 'Product Type',
		'note'              => '',
        'type'              => 'int',	//backend_type
		'input'             => 'select',	//frontend_input
		'frontend_class'	=> '',
		'source'			=> 'sourcetype/attribute_source_type',
        'backend'           => '',
        'frontend'          => '',
        'global'            => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_WEBSITE,
		'required'          => true,
        'visible_on_front'  => false,
        'apply_to'          => 'simple',
        'is_configurable'   => false,
        'used_in_product_listing'	=> false,
        'sort_order'        => 5,
    ));
 
$installer->endSetup();

After that you need to create custom source type or php class with name: “Inchoo_Sourcetype_Model_Attribute_Source_Type“. Take a look at my example below.

class Inchoo_Sourcetype_Model_Attribute_Source_Type extends Mage_Eav_Model_Entity_Attribute_Source_Abstract
{
	const MAIN = 1;
	const OTHER = 2;
 
    public function getAllOptions()
    {
        if (is_null($this->_options)) {
            $this->_options = array(
                array(
                    'label' => Mage::helper('sourcetype')->__('Main Product'),
                    'value' =>  self::MAIN
                ),
                array(
                    'label' => Mage::helper('sourcetype')->__('Other Product'),
                    'value' =>  self::OTHER
                ),
            );
        }
        return $this->_options;
    }
 
    public function toOptionArray()
    {
        return $this->getAllOptions();
    }
 
    public function addValueSortToCollection($collection, $dir = 'asc')
    {
        $adminStore  = Mage_Core_Model_App::ADMIN_STORE_ID;
        $valueTable1 = $this->getAttribute()->getAttributeCode() . '_t1';
        $valueTable2 = $this->getAttribute()->getAttributeCode() . '_t2';
 
        $collection->getSelect()->joinLeft(
            array($valueTable1 => $this->getAttribute()->getBackend()->getTable()),
            "`e`.`entity_id`=`{$valueTable1}`.`entity_id`"
            . " AND `{$valueTable1}`.`attribute_id`='{$this->getAttribute()->getId()}'"
            . " AND `{$valueTable1}`.`store_id`='{$adminStore}'",
            array()
        );
 
        if ($collection->getStoreId() != $adminStore) {
            $collection->getSelect()->joinLeft(
                array($valueTable2 => $this->getAttribute()->getBackend()->getTable()),
                "`e`.`entity_id`=`{$valueTable2}`.`entity_id`"
                . " AND `{$valueTable2}`.`attribute_id`='{$this->getAttribute()->getId()}'"
                . " AND `{$valueTable2}`.`store_id`='{$collection->getStoreId()}'",
                array()
            );
            $valueExpr = new Zend_Db_Expr("IF(`{$valueTable2}`.`value_id`>0, `{$valueTable2}`.`value`, `{$valueTable1}`.`value`)");
 
        } else {
            $valueExpr = new Zend_Db_Expr("`{$valueTable1}`.`value`");
        }
 
 
 
        $collection->getSelect()
            ->order($valueExpr, $dir);
 
        return $this;
    }
 
    public function getFlatColums()
    {
        $columns = array(
            $this->getAttribute()->getAttributeCode() => array(
                'type'      => 'int',
                'unsigned'  => false,
                'is_null'   => true,
                'default'   => null,
                'extra'     => null
            )
        );
        return $columns;
    }
 
 
    public function getFlatUpdateSelect($store)
    {
        return Mage::getResourceModel('eav/entity_attribute')
            ->getFlatUpdateSelect($this->getAttribute(), $store);
    }
}

If setup has finished properly you would need to have attribute in Magento admin with drop-down menu with two options, take look at the next my screen shoot:
Go to Magento admin -> Catalog -> Product and create new simple product, you will see new tab with name “Product Options”.

You made it all the way down here so you must have enjoyed this post! You may also like:

Enhanced Catalog Product Grid – Custom Attribute Filter Milovan Gal
Milovan Gal, | 55

Enhanced Catalog Product Grid – Custom Attribute Filter

Add custom attribute to Magento’s PDF invoice Mladen Lotar
Mladen Lotar, | 66

Add custom attribute to Magento’s PDF invoice

Listing products by attribute Vanja Devcic
Vanja Devcic, | 8

Listing products by attribute

13 comments

  1. Hi,
    I tried this tutorial, I am facing problem when I am going to edit the product.
    Select field need to selected previous value when I click to edit product but instead of that it showing first value of options, Value is saving correctly, I am getting it in front end as well, But it has to selected value by default when edit.
    Help me

  2. can i do the same but with customer?
    I tried it, but the custom field is added in account information tab and not in the new custom tab.
    thanks

  3. If I change the type to “varchar” and the input to “multiselect” I can no longer save values for that attribute. Any idea why?

  4. how to make a cascading dropdown from that “Product Type” dropdown?
    so when user select a value, another dropdown shows up underneath it and load values based on the selection.
    I can’t find this anywhere in google.

    thanks

  5. Hello
    I tried to do according to that example but i understood that it would be better to use extension for customers attributes. Why? because you shouldn’t look into tons of codes and terms ( maybe because i’m a newbie in programming).

    but all in all i’m convinced that extension makes life more easy.

    what concerns me i use amasty’ extension for customer attributes and some more.

  6. Please tell me location for where i should create this file Inchoo_Sourcetype_Model_Attribute_Source_Type

  7. Thanks.

    How can I set the default value ?

    $installer->addAttribute(‘
    ‘default’ => ‘Sub Product’
    “);

    It seems not working.

  8. I would also be interested in showing this type of attributes within the layered navigation.. can’t get this to work

  9. Will this attribute then be used in Layered Navigation? Or is there something missing. I’ve been trying this out. But can’t get the attribute visible in Layered Navigation. Yes, all the required settings/product data is there in place.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <blockquote cite=""> <code> <del datetime=""> <em> <s> <strike> <strong>. You may use following syntax for source code: <pre><code>$current = "Inchoo";</code></pre>.

Tell us about your project

Drop us a line. We'd love to know more about your project.