We often use the multi-select box in the system configuration. We can show a list of countries, states, shipping methods, payment methods, or anything else that needs to be configured from the admin side.
A prevalent example is allowing several countries to check out. We are often required to create such a configuration in the admin area. However, we notice that rollback is impossible by unselecting selected values once we select options and click save.
In other words, we are required to select at least one option. Otherwise, changes will be unsaved, and we will see the same values on the screen again.
In such a scenario, we often add the option at the start with a blank value in the multi-select box. Although this is an acceptable solution, there should still be some mechanism to unselect all the options.
Yes, there should be a mechanism. Magento already provides a solution, which we will discuss in this post.
Magento 2: Allow admins to unselect in multi-select system configuration
The solution is straightforward. Just like we add labels, validation, or notes in our admin configuration, we must add the line below inside our configuration field.
<can_be_empty>1</can_be_empty>
That’s the solution. Pass 1 as an argument inside the XML tag <can_be_empty>, and Magento 2 will allow the user to unselect all values.
The default value is 0, meaning we cannot unselect all options by default. To allow the admin to unselect all options, we must pass 1 as a value.
Example:
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Config:etc/system_file.xsd">
<system>
<section id="sbdevblog">
<group id="example" translate="label" type="text" sortOrder="10" showInDefault="1" showInWebsite="1"
showInStore="1">
<field id="multiselect" translate="Example Of Multiselect" type="multiselect" sortOrder="10"
showInDefault="1" showInWebsite="1"
showInStore="1">
<label>Multi Select Example</label>
<source_model>SbDevBlog\Example\Ui\Component\Listing\column\Multiselect</source_model>
</field>
</group>
</section>
</system>
</config>
I hope you have liked the post: Magento 2: Allow admins to unselect in multi-select system configuration. Please stay tuned to SBDEVBLOG.
Use the comment box for your feedback, and please share SbDevBlog with connections. Thank you.
Click here to create a dynamic row configuration: https://sbdevblog.com/magento-2-create-dynamic-row-system-configuration/