Usage of <can_be_empty> tag for system configuration multi-select field

October 22, 2011  |  2 Comments  |  by Raj (MagePsycho)  |  Latest, Magento

Suppose say you have following multi-select field in System > Configuration:

Multi-Select Field - Customer Groups

Multi-Select Field - Customer Groups

which is defined by following xml code (partial):
File: app/code/local/MagePsycho/Demomodule/etc/system.xml

...
<allowed_groups translate="label">
	<label>Main Website / Main Store / English</label>
	<frontend_type>multiselect</frontend_type>
	<source_model>demomodule/system_config_source_customergroups</source_model>
	<sort_order>10</sort_order>
	<show_in_default>1</show_in_default>
	<show_in_website>1</show_in_website>
	<show_in_store>1</show_in_store>
</allowed_groups>
...

When you try to de-select the only one selected option from multi-select field(refer the above snap) and save the config, you will notice that option is not de-selected. In short, config cannot save multi-select field with empty selection. You may feel that it’s a bug in magento but unfortunately it’s not a bug, it’s a feature :). If you want to select none of the options from multi-select field, you need to use the tag: <can_be_empty> with value = 1 as:

...
<allowed_groups translate="label">
	<label>Main Website / Main Store / English</label>
	<frontend_type>multiselect</frontend_type>
	<source_model>demomodule/system_config_source_customergroups</source_model>
	<sort_order>10</sort_order>
	<show_in_default>1</show_in_default>
	<show_in_website>1</show_in_website>
	<show_in_store>1</show_in_store>
	<can_be_empty>1</can_be_empty><!-- Note this line -->
</allowed_groups>
...

So from above it is clear that usage of <can_be_empty> with value 1 allows the empty selection for multi-select field.
The logic behind this goes as:
if <can_be_empty> is true, the system renders a hidden field on the System Configuration page
File: lib/Varien/Data/Form/Element/Multiselect.php

if ($this->getCanBeEmpty()) {
    $html .= '<input type="hidden" name="' . parent::getName() . '" value="" />';
}

[Ref: In Depth Magento System Configuration]

Hope this demystyfies the usage of <can_be_empty> for system configuration multi-select field.

Thanks for reading.

Posted in Latest, Magento. Bookmark the permalink.

About Raj (MagePsycho)

Raj, the guy behind MagePsycho is a Zend PHP5 Certified Engineer, Magento Certified Developer, Magento Moderator / Freelancer with specialization in web applications (CMS, E-Commerce, ERP etc.). Catch him on: Twitter: @magepsycho Skype: magentopycho
  • http://atwix.com Alex

    Good catch, I had the same issue when implementing custom source model for multi select attribute and had to add code which checked the post data for the attribute. I suppose <can_be_empty> can be applied for this case to, will have a look into it.

    Thanks for the insight!

  • Dan Ilie

    Great observation. Thnx!