Magento 1.9 – What is a Source Model?

magento-1.9modelsource-model

Can anyone explain what is a source Model in Magento.

various time it was asked by interviewer …but it was confusing for me…can any body explain…..
I need to know deeply about source model.. in Magento and its task…..
I know about resource model which is responsible for collection and model for basic logic…but source model I don not know…..pls help

Best Answer

A source model is the source of possible values for dropdown or multiselect form fields. Each value is a pair of actual value and displayed label. Source models are used for, but not limited to:

  • system configuration values
  • attribute values
  • grid column filters
  • custom Varien_Form instances

There are a few methods a source model should implement, depending on the context. Magento 1 was not very keen on interfaces, so this is basically just a halfway consistent convention1. If you want to create a generic source model that can be used anywhere, make sure to implement them all:

  • toOptionArray() returns an array of arrays, each must have the keys label and value. You can nest the arrays one level deeper to define <optgroup> groups
  • toOptionHash() returns an associative array in the form value => label
  • getAllOptions($withEmpty) same as toOptionArray(), but you can specify if an empty value with 'Please choose...' label is added.
  • getOptionText($value) returns the label for a given value

1) There is Mage_Eav_Model_Entity_Attribute_Source_Interface but it is only sufficient for EAV attributes and not type hinted anywhere.