lightning-datatable with batch updates handled by a custom Apex controller.
Overview
This example demonstrates how to:- Enable inline editing on datatable columns
- Handle save events with draft values
- Update multiple records using Apex
- Refresh data after successful updates
- Display toast notifications for success/error states
Component Code
JavaScript Controller
datatableInlineEditWithApex.js
Template
datatableInlineEditWithApex.html
Apex Controller
ContactController.cls
Key Features
Editable Columns
Seteditable: true on column definitions:
Draft Values
Track pending edits with thedraft-values attribute:
Save Handler
Theonsave event provides draft values:
Refresh Data
UserefreshApex to reload wired data:
Implementation Steps
- Define editable columns - Add
editable: trueto column definitions - Track draft values - Initialize
draftValues = []property - Handle save event - Implement
handleSavemethod - Call Apex - Pass draft values to Apex controller
- Clear drafts - Reset
draftValuesafter save - Refresh data - Use
refreshApexto reload records - Show feedback - Dispatch toast events for success/error
Comparison with UI API
| Feature | Apex Approach | UI API Approach |
|---|---|---|
| Update Method | Custom Apex method | updateRecord from lightning/uiRecordApi |
| Batch Updates | Single Apex call | Parallel Promise.all |
| Custom Logic | Supports complex business logic | Standard CRUD operations |
| FLS/Security | Manual enforcement | Automatic enforcement |
| Use Case | Complex updates, validations | Simple field updates |
Best Practices
- Always clear
draftValuesafter processing - Implement proper error handling
- Refresh data after successful updates
- Provide user feedback with toast notifications
- Enforce field-level security in Apex
- Use
async/awaitfor cleaner asynchronous code
Related Components
Source
datatableInlineEditWithApex.js:7-12- Editable column definitionsdatatableInlineEditWithApex.js:22-52- Save handler implementationContactController.cls:44-52- Apex update method
