Magento 2 UI Component – Disabling a Field Based on Condition

fieldsetsmagento2modeluicomponent

I have a UI component defining some fields. How do I disable the field upon a certain condition? In other words, use <item name="disabled" xsi:type="boolean">true</item> only when a condition is met. Here's my field.

<field name="name">
        <argument name="data" xsi:type="array">
            <item name="config" xsi:type="array">
                <item name="dataType" xsi:type="string">text</item>
                <item name="label" xsi:type="string" translate="true">Profile Name</item>
                <item name="formElement" xsi:type="string">input</item>
                <item name="source" xsi:type="string">profile</item>
                <item name="dataScope" xsi:type="string">name</item>
            </item>
        </argument>
    </field>

Best Answer

First set:

<item name="disabled" xsi:type="string">${ $.provider }:data.do_we_hide_it</item>

Suppose Vendor\Extension\Model\Notification\DataProvider is your data provider for UI:

<dataSource name="notification_edit_data_source">
    <argument name="dataProvider" xsi:type="configurableObject">
        <argument name="class" xsi:type="string">Vendor\Extension\Model\Notification\DataProvider</argument>
        <argument name="name" xsi:type="string">notification_edit_data_source</argument>

Then in its getData function add the following lines:

public function getData(){
.....
.....
if(condition1)
    $this->loadedData[$entity_id]['do_we_hide_it'] = true;
else
    $this->loadedData[$entity_id]['do_we_hide_it'] = false;

See the core files vendor/magento/module-catalog/view/adminhtml/ui_component/category_form.xml line 377 and vendor/magento/module-catalog/Model/Category/DataProvider.php line 303 for an example.

Related Topic