Magento uses source models as a means of gathering data from either the database or from files, and displaying the data against a specific field. We can also add a Magento custom source model using a custom module. Examples of existing source models in Magento include the following.
catalog/product_status
– used for the Status attribute in the eav_attribute
tableadminhtml/system_config_source_country
– used for displaying countries configured in system.xml
in the Mage_Shipping
module.Within the catalog/product_status
model, we can see that the Enabled
and Disabled
options are defined here.
<?php class Mage_Catalog_Model_Product_Status extends Mage_Core_Model_Abstract { .... static public function getOptionArray() { return array( self::STATUS_ENABLED => Mage::helper('catalog')->__('Enabled'), self::STATUS_DISABLED => Mage::helper('catalog')->__('Disabled') ); }
And within the adminhtml/system_config_source_country
model, the countries are obtained from the directory/country_collection
resource model.
<?php class Mage_Adminhtml_Model_System_Config_Source_Country { protected $_options; public function toOptionArray($isMultiselect=false) { if (!$this->_options) { $this->_options = Mage::getResourceModel('directory/country_collection')->loadData()->toOptionArray(false); } $options = $this->_options; if(!$isMultiselect){ array_unshift($options, array('value'=>'', 'label'=> Mage::helper('adminhtml')->__('--Please Select--'))); } return $options; } }
So if we wanted to create our very own source model, we would need to create a simple module that contained a source model.
To start with, add the module’s activation file.
<?xml version="1.0"?> <config> <modules> <Custom_Sourcemodel> <codePool>local</codePool> <active>true</active> </Custom_Sourcemodel> </modules> </config>
Then declare the model path in the module’s config.xml
file.
<?xml version="1.0"?> <config> <global> <models> <sourcemodel> <class>Custom_Sourcemodel_Model</class> </sourcemodel> </models> </global> </config>
Note that the naming conventions for source models that are involved in the System -> Configuration
area are as follows: adminhtml_system_config_source_[model]
.
If we follow this convention, and have a simple Colour.php
model that will return three colours.
<?php class Custom_Sourcemodel_Model_Adminhtml_System_Config_Source_Colour extends Mage_Eav_Model_Entity_Attribute_Source_Abstract { public function getAllOptions() { $colours = array( array('value' => 'red', 'label' => 'Red'), array('value' => 'blue', 'label' => 'Blue'), array('value' => 'green', 'label' => 'Green'), ); return $colours; } }
Note that source models should extend the Mage_Eav_Model_Entity_Attribute_Source_Abstract
class.
Now that we have this in place, we can add the source model to a field within system.xml
, and populate its source model to be the following.
<source_mode>sourcemodel/adminhtml_system_config_source_colour</source_model>
Note: This article is based on Magento Community/Open Source version 1.9.