2
votes

I tried to search this but couldn't find any. When creating a custom product attribute with select type programmatically, Magento always assigns eav/entity_attribute_source_table as the source model.

There are 2 issues with this default source model:

  1. I can't auto populate the field with data taken programmatically from somewhere else other than have to type the data list manually one by one.

  2. Although I have specified the "default" or "default_value" (I can see in the database that the value is there), the field is still showing empty as the first line.

How I can change the default source_model to my own source model for select type?

Thank you

3

3 Answers

3
votes

The key you are looking for is to pass a source value in your SQL setup. Make sure your $installer is an EAV setup object.

You would do the following in your setup script:

$installer = $this;

$installer->starSetup();

// Setup customer multiselect attribute
$attr = array(
    'backend'      => 'eav/entity_attribute_backend_array',
    'input'        => 'multiselect',
    'label'        => 'Permissions',
    'note'         => 'Used for group-based frontend permissions.',
    'required'     => false,
    'sort_order'   => '1000',
    'source'       => 'eav/entity_attribute_source_table', // Change it here
    'user_defined' => true
);
$installer->addAttribute('customer', 'permissions', $attr);

// Add options for permissions
$options = array(
    'attribute_id' => $installer->getAttributeId('customer', 'permissions'),
    'value' => array(
        'place_order'    => array('Can Place Orders'),
        'view_catalog'   => array('Can View the Catalog'),
    )
);
$installer->addAttributeOption($options);

$installer->endSetup();

Utimately, I believe the source model can be anything that provides a toOptionArray() function.

0
votes

There is a great example of this in Mage_Customer, installer: mysql4-upgrade-1.5.9.9-1.6.0.0.php

In it, a country source model is being assigned to customer address attribute country_id.

$installer->updateAttribute(
    'customer_address',
    'country_id',
    'source_model',
    'customer/entity_address_attribute_source_country'
);

Change this to catalog_product, your attribute, and source model.

0
votes

You set the source type as shown below.

'source'        => 'categoryattr/attribute_source_type',

and create the file Attribute\Source\Type.php and the create the options and set the value 0 for default option.

 $this->_options[] = array (
            'label' => 'Select Category',
            'value' => '0'
        );

please refer below for file structure and step by step explanation.

http://www.pearlbells.co.uk/how-to-create-custom-attribute-source-type-in-magento/