Unable to save blank multiselect value in system configuration in Magento 2
-
06-03-2021 - |
Question
I have created multiselect in system.xml
with backend_model
and customize afterSave
function and return parent::afterSave()
.
<field id="populatavailablebanknetbanking" translate="label" type="multiselect" sortOrder="30" showInDefault="1" showInWebsite="1" showInStore="1">
<label>Available Bank for Netbanking (Popular)</label>
<source_model>Vendor\Module\Model\Config\Availablebanknetbanking</source_model>
<backend_model>Vendor\Module\Model\Config\Backend\Popularbanknetbanking</backend_model>
<comment>This selected depends on the Available Bank for Netbanking options. You can only select from the selection made above for the popular bank.</comment>
</field>
It's working fine with saving multiselect value in the database but when I unselect all the options from multiselect, it saves recently saved options from the database instead of clear the options from the database.
No correct solution
OTHER TIPS
You can use:
<can_be_empty>1</can_be_empty>
Like:
<field id="list" translate="label" type="multiselect" sortOrder="3" showInDefault="1" showInWebsite="1" showInStore="0">
<label>Customer Groups</label>
<source_model>Commercepundit\Simpleshipping\Model\Adminhtml\System\Config\Source\Customer\Group</source_model>
<can_be_empty>1</can_be_empty>
</field>
Magento have property <can_be_empty>
. Which allows you to save blank value in database.
<field id="populatavailablebanknetbanking" translate="label" type="multiselect" sortOrder="30" showInDefault="1" showInWebsite="1" showInStore="1">
<label>Available Bank for Netbanking (Popular)</label>
<source_model>Vendor\Module\Model\Config\Availablebanknetbanking</source_model>
<backend_model>Vendor\Module\Model\Config\Backend\Popularbanknetbanking</backend_model>
<can_be_empty>1</can_be_empty>
<comment>This selected depends on the Available Bank for Netbanking options. You can only select from the selection made above for the popular bank.</comment>
</field>
The
<can_be_empty/>
tag is used with multiselect fields. The short version is, if you wish to a allow “no selection” to be a valid configuration, use this field.What happens behind the scenes is 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="" />';
}
which ensure the form processing code will accept an empty selection.