Magento Admin – System.xml ‘Select’ Field and $addEmpty Parameter

adminbackendmodelsystem.xml

I was wondering if it is possible to pass parameters to the source model from the system.xml. This is how my system.xml currently looks like:

                <category>
                    <label>Category</label>
                    <frontend_type>select</frontend_type>
                    <sort_order>3</sort_order>
                    <source_model>adminhtml/system_config_source_category</source_model>
                    <comment>I live</comment>
                    <show_in_default>1</show_in_default>
                    <show_in_website>1</show_in_website>
                    <show_in_store>1</show_in_store>
                </category>

It works but I have no empty value at the top of the dropdown because I cant pass the boolean parameter true to the source model. Just to make things easy, this is the source model:

<?php


class Mage_Adminhtml_Model_System_Config_Source_Category
{
    public function toOptionArray($addEmpty = true)
    {
        $tree = Mage::getResourceModel('catalog/category_tree');

        $collection = Mage::getResourceModel('catalog/category_collection');

        $collection->addAttributeToSelect('name')
            ->addRootLevelFilter()
            ->load();

        $options = array();

        if ($addEmpty) {
            $options[] = array(
                'label' => Mage::helper('adminhtml')->__('-- Please Select a Category --'),
                'value' => ''
            );
        }
        foreach ($collection as $category) {
            $options[] = array(
               'label' => $category->getName(),
               'value' => $category->getId()
            );
        }

        return $options;
    }
}

Best Answer

I think this is a bug or someone overlooked this:
The call to toOptionArray receives the parameter $fieldType == 'multiselect': https://github.com/OpenMage/magento-mirror/blob/magento-1.9/app/code/core/Mage/Adminhtml/Block/System/Config/Form.php#L463 So the empty option is added only if the type of the field is multiselect. From my point of view it should be the other way around. It should be added for simple selects and not added to multiselects.

Since you cannot edit the core, and you would not want to override the method linked above The solution would be to create your own source model that calls the source model you mentioned and just adds an empty option at the top.

So add this class in one of your modules:

<?php 
class [Namespace]_[Module]_Model_System_Config_Source_Category
{
    public function toOptionArray()
    {
        return Mage::getModel('adminhtml/system_config_source_category')->toOptionArray(true);
    }
}

then declare your system.xml field like this

....
<source_model>[module]/system_config_source_category</source_model>
....