Disabling a UI component field upon condition in Magento 2

I tried Konstantin's solution but for some reason, it didn't work for me.

I managed to make it work by using the following syntax:

<field name="name">
    <argument>
      ...
    </argument>
    <settings>
        <imports>
            <link name="disabled">${ $.provider}:data.do_we_hide_it</link>
        </imports>
    </settings>
</field>

Hope it helps.

Edit :

The argument node is not required but if it exists, settings node must be placed after. It is the last one in the xsd definition in M2.3. The xml comes in addition with the accepted 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.


You can override getMeta() function in your DataProvider class

public function getMeta()
    {
        $meta = parent::getMeta();
        $id = $this->request->getParam('entity_id');
        if(isset($id)){

           $meta['fieldset_name']['children']['field_name']['arguments']['data']['config']['visible'] = 1;


        }
        else{
           $meta['fieldset_name']['children']['field_name']['arguments']['data']['config']['visible'] = 0;


        }
        return $meta;
    }

This worked for me.