# Lightning Datatable

# 📊 Lightning Data Table in Lightning Web Components (LWC)

The `lightning-datatable` component in LWC provides a rich, flexible way to display tabular data, supporting features like **column formatting**, **inline editing**, **sorting**, and more — all without writing much custom HTML or JavaScript.

---

## 🌟 What Is `lightning-datatable`?

The `lightning-datatable` is a powerful base component that renders a responsive table using the data and metadata you provide. It’s commonly used for displaying Salesforce records with built-in support for **inline editing**, **custom formatting**, and **row-level actions**.

---

## 🔧 Essential Attributes of `lightning-datatable`

| Attribute | Description |
| --- | --- |
| `key-field` | A **unique identifier** for each row, typically the record ID (`Id`). Required. |
| `data` | The **array of data records** to display in the table. |
| `columns` | An **array of column definitions** (labels, field names, types, sortability, etc.). |
| `hide-checkbox-column` | (Optional) Hides the row selection checkbox. |
| `draft-values` | Used for **inline editing** to track modified fields. |
| `onsave` | JavaScript handler for **saving edited data** when inline editing is used. |

---

## ✅ Simple Lightning Data Table Example

This example shows a basic data table that displays account data retrieved from Apex.

### 🧩 HTML – `lightningDatatableComponent.html`

```html
<template>
    <lightning-card title="Lightning Data Table">
        <lightning-datatable
            data={fetchedAccounts}
            columns={columns}
            key-field="Id">
        </lightning-datatable>
    </lightning-card>
</template>
```

### 🧩 JavaScript – `lightningDatatableComponent.js`

```js
import { LightningElement, wire } from 'lwc';
import accountRecords from '@salesforce/apex/ControllerClass.accountRecords';

export default class LightningDatatableComponent extends LightningElement {
    fetchedAccounts;

    columns = [
        { label: 'Account Name', fieldName: 'Name', type: 'text', sortable: true },
        { label: 'Type', fieldName: 'Type', type: 'text', sortable: true },
        { label: 'Annual Revenue', fieldName: 'AnnualRevenue', type: 'currency', sortable: true },
        { label: 'Phone', fieldName: 'Phone', type: 'phone', sortable: true },
        { label: 'Website', fieldName: 'Website', type: 'url', sortable: true },
        { label: 'Rating', fieldName: 'Rating', type: 'text', sortable: true }
    ];

    @wire(accountRecords)
    wiredAccounts({ error, data }) {
        if (data) {
            this.fetchedAccounts = data;
        } else if (error) {
            console.error('Error fetching accounts:', error);
        }
    }
}
```

### 🧩 Apex Controller – `ControllerClass.cls`

```plaintext
public class ControllerClass {
    @AuraEnabled(cacheable=true)
    public static List<Account> accountRecords() {
        return [
            SELECT Id, Name, Rating, Website, Type, AnnualRevenue, Phone
            FROM Account
        ];
    }
}
```

---

## ✏️ Lightning Data Table With Inline Editing

`lightning-datatable` also supports **inline editing**, allowing users to update field values directly in the table without navigating to the record detail page.

### 🧩 HTML – `lightningDatatableComponent.html`

```html
<template>
    <lightning-card title="Lightning Data Table with Inline Editing">
        <lightning-datatable
            data={fetchedAccounts}
            columns={columns}
            key-field="Id"
            hide-checkbox-column
            draft-values={draftValues}
            onsave={handleSave}>
        </lightning-datatable>
    </lightning-card>
</template>
```

### 🧩 JavaScript – `lightningDatatableComponent.js`

```js
import { LightningElement, wire } from 'lwc';
import accountRecords from '@salesforce/apex/ControllerClass.accountRecords';
import updateAccounts from '@salesforce/apex/ControllerClass.updateAccounts';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';

export default class LightningDatatableComponent extends LightningElement {
    fetchedAccounts;
    draftValues = [];

    columns = [
        { label: 'Account Name', fieldName: 'Name', type: 'text', editable: true, sortable: true },
        { label: 'Type', fieldName: 'Type', type: 'text', sortable: true },
        { label: 'Annual Revenue', fieldName: 'AnnualRevenue', type: 'currency', sortable: true },
        { label: 'Phone', fieldName: 'Phone', type: 'phone', sortable: true },
        { label: 'Website', fieldName: 'Website', type: 'url', sortable: true },
        { label: 'Rating', fieldName: 'Rating', type: 'text', sortable: true }
    ];

    @wire(accountRecords)
    wiredAccounts({ error, data }) {
        if (data) {
            this.fetchedAccounts = data;
        } else if (error) {
            console.error('Error fetching accounts:', error);
        }
    }

    handleSave(event) {
        const updatedFields = event.detail.draftValues;

        updateAccounts({ data: updatedFields })
            .then(() => {
                this.dispatchEvent(
                    new ShowToastEvent({
                        title: 'Success',
                        message: 'Accounts updated successfully.',
                        variant: 'success'
                    })
                );
                this.draftValues = [];
            })
            .catch(error => {
                this.dispatchEvent(
                    new ShowToastEvent({
                        title: 'Error',
                        message: 'Failed to update records.',
                        variant: 'error'
                    })
                );
                console.error('Update error:', error);
            });
    }
}
```

### 🧩 Apex Controller – `ControllerClass.cls`

```plaintext
public class ControllerClass {

    @AuraEnabled(cacheable=true)
    public static List<Account> accountRecords() {
        return [
            SELECT Id, Name, Rating, Website, Type, AnnualRevenue, Phone
            FROM Account
        ];
    }

    @AuraEnabled
    public static void updateAccounts(Object data) {
        List<Account> updatedAccounts = 
            (List<Account>) JSON.deserialize(JSON.serialize(data), List<Account>.class);
        update updatedAccounts;
    }
}
```

---

## 🧠 Conclusion

`lightning-datatable` is a robust and flexible component that lets you build data-rich experiences quickly in LWC. With support for formatting, inline editing, sorting, and more, it is perfect for displaying records in a structured, user-friendly way.

### 🚀 Key Takeaways:

* Use `columns` to define the structure and formatting of the data.
    
* Use `draft-values` and `onsave` for inline editing.
    
* Leverage Apex with `@wire` or imperative calls for dynamic data loading and updates.
    
* Don’t forget to handle errors and success messages with `ShowToastEvent`.
