[SalesForce] LWC Lightning datatable – Conditionally disable-enable cell

I want to conditionally control the inline editing property of the Quantity column.

Followed many posts Conditionally enable edit in lightning:datatable, https://developer.salesforce.com/forums/?id=9062I000000QxLq and many more but to no avail. Here is my css

.testone{
    pointer-events: none;
    color: #333;
    border: 1px solid #666;
    background: red;
 }

and the Quantity column has the cellAttributes element

        {label: labels.quantity, fieldName: 'Quantity', type: 'number', editable : true,
            cellAttributes: {
                class:{
                    fieldName: 'testone'
                }
            }
        },

and the js code where the items are fed to the data property of the datatable,

            let  items =[];
            this._cached.forEach(item => {
                item.testone = 'testone';

                items.push(item);
            });

the datatable is rendering correctly but the Quantity is always editable when it shouldn't. Any idea where I am going wrong?

I can see the css being applied, see the screenshot below.
[![chrome inspector screenshot][1]]
[1]: https://i.stack.imgur.com/sQmw8.png

Best Answer

Here's a solution using an attribute for the editable value

You can conditionally edit by doing the following in the LWC datatable:

In your table columns define editable as such

COLUMN = [
{label: 'Quantity, fieldName: 'Quantity__c', type: 'number', sortable: false, editable: {fieldName: 'controlEditField'}]

In your data include the controlling field like

data = {
   Quantity__c: 'Some Value',
   controlEditField: false
}

You can manipulate the controlling field via JS or in your Apex logic.

Please note: You can debug this feature using the Chrome Developer Tools and enabling your Salesforce Sandbox user for Debug Mode. You can then open datatable.js to look under the hood at how this resolves. See the function isCellEditable.

Related Topic