How to Add a Picklist In LWC Data Table?

In the Salesforce Lightning data table, we don’t have a defined data type to display picklist values in the LWC data table. To add picklist values to a Lightning data table, we need to define a custom data type to display the picklist field.

In this Salesforce tutorial, we will learn how to add a picklist in an LWC data table, and for this, we will also use the combo-box feature to display picklist values.

Picklist Field in Salesforce LWC Data Table

In Salesforce Lightning LWC data tables, the picklist values are displayed in a dropdown menu that allows users to select a single value from a predefined list of options. This feature of displaying a picklist is integrated into the LWC data tables to perform inline editing directly from the table rows.

Add a Picklist in Salesforce LWC Data Table

In the example below, we will create an LWC data table, fetching the account records along with the picklist field Industry.

  1. We will fetch the account records, so we need to create a controller class to fetch them. We also need to fetch the values of the picklist field, Industry.

For that, create an Apex class and enter the code below.

public with sharing class AccountController {
    @AuraEnabled(cacheable=true)
    public static List<Account> getAccounts() {
        return [SELECT Id, Name, Industry FROM Account LIMIT 10];
    }

    @AuraEnabled(cacheable=true)
    public static List<Map<String, String>> getIndustryOptions() {
        List<Map<String, String>> options = new List<Map<String, String>>();
        Schema.DescribeFieldResult fieldResult = Account.Industry.getDescribe();
        List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();
        for (Schema.PicklistEntry entry : ple) {
            options.add(new Map<String, String>{'label' => entry.getLabel(), 'value' => entry.getValue()});
        }
        return options;
    }
}
  1. After this, create an LWC component and enter the code below in the JS file. This will handle the logic of displaying the Account Name and Industry columns in the Data table, and also showing the values of the picklist in the dropdown.

This will be the main LWC component accountDataTable. To define a custom type for Industry, we have a type, customCombo, that is again an LWC that we will define in the next steps.

import { LightningElement, wire, track } from 'lwc';
import getAccounts from '@salesforce/apex/AccountController.getAccounts';
import getIndustryOptions from '@salesforce/apex/AccountController.getIndustryOptions';
import { updateRecord } from 'lightning/uiRecordApi';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';

const columns = [
    { label: 'Account Name', fieldName: 'Name', type: 'text' },
    {
        label: 'Industry',
        fieldName: 'Industry',
        type: 'customCombo',
        wrapText: true,
        editable: true,
        typeAttributes: {
            options: { fieldName: 'industryOptions' },
            value: { fieldName: 'Industry' }
        }
    }
];

export default class AccountDataTable extends LightningElement {
    @track accounts = [];
    @track draftValues = [];
    
    columns = columns;

    @wire(getAccounts)
    wiredAccounts({ error, data }) {
        if (data) {
            this.processAccounts(data);
        } else if (error) {
            this.showToast('Error', 'Error loading accounts', 'error');
        }
    }

    @wire(getIndustryOptions)
    wiredIndustryOptions({ error, data }) {
        if (data) {
            this.industryOptions = data;
            this.processAccounts(this.accounts);
        } else if (error) {
            this.showToast('Error', 'Error loading industry options', 'error');
        }
    }

    processAccounts(data) {
        if (this.industryOptions && data) {
            this.accounts = data.map(account => ({
                ...account,
                industryOptions: this.industryOptions
            }));
        }
    }

    handleRowAction(event) {
        const { rowId, value } = event.detail;
        this.draftValues = [{ Id: rowId, Industry: value }];
    }

    async handleSave(event) {
        const updatedFields = event.detail.draftValues.slice()[0];
        const recordInput = { fields: updatedFields };

        try {
            await updateRecord(recordInput);
            this.draftValues = [];
            this.showToast('Success', 'Account updated', 'success');
        } catch (error) {
            this.showToast('Error', error.body.message, 'error');
        }
    }

    showToast(title, message, variant) {
        this.dispatchEvent(new ShowToastEvent({ title, message, variant }));
    }
}
  1. After this, enter the code below in the HTML file accountDataTable.html.
<template>
    <lightning-card title="Accounts with Industry Combobox" icon-name="standard:account">
        <div class="slds-m-around_medium">
            <c-enhanced-data-table
                key-field="Id"
                data={accounts}
                columns={columns}
                onrowaction={handleRowAction}
                draft-values={draftValues}
                onsave={handleSave}>
            </c-enhanced-data-table>
        </div>
    </lightning-card>
</template>
  1. Since lightning-datatable doesn’t natively support lightning-combobox, we’ll create a custom component for the combobox column.

Enter the code below in the JS file to handle the logic of displaying the individual picklist values in the data table on the dropdown.

export default class ComboBoxCell extends LightningElement {
    @api value;     
    @api options;    

    handleChange(event) {
        const changeEvent = new CustomEvent('valuechange', {
            detail: { value: event.detail.value }
        });
        this.dispatchEvent(changeEvent);
    }
}

Here, @api value tracks the current picklist values, and @options handles the available picklist options. Then, the event handleChange dispatches the selected value to the parent component.

  1. In the comboBox.html, enter the code below. We have used lightning-combobox for the picklist UI, and it binds values and options using the event handleChange.
<template>
    <lightning-combobox
        value={value}
        options={options}
        onchange={handleChange}>
    </lightning-combobox>
</template>
  1. Create another LWC component, enhancedDataTable, to handle rendering the types or values of the picklist.

Enter the code below in the enhancedDataTable.js file.

import LightningDatatable from 'lightning/datatable';
import comboBoxCellTemplate from './comboBoxCellTemplate.html';

export default class EnhancedDataTable extends LightningDatatable {
    static customTypes = {
        customCombo: {
            template: comboBoxCellTemplate,
            typeAttributes: ['options', 'value']
        }
    };

    handleClick(event) {
        console.log('Cell clicked, rowId:', event.target.dataset.rowId);
    }

    handleChange(event) {
        const rowId = event.target.dataset.rowId;
        const newValue = event.detail.value;
        this.dispatchEvent(new CustomEvent('rowaction', {
            detail: { rowId, value: newValue }
        }));
    }
}

In the above code, we have defined the events handleClick and handleChange, which handle the change and the click event, and execute the changes to the main component.

  1. In the same LWC component enhancedDataTable, create an HTML file named comboBoxCellTemplate.html and enter the code below.
<template>
    <c-combo-box-cell
        value={typeAttributes.value}
        options={typeAttributes.options}
        data-row-id={rowKeyValue}
        onchange={handleChange}
        onclick={handleClick}>
    </c-combo-box-cell>
</template>

This links EnhancedDataTable and ComboBoxCell, rendering a picklist in each Industry column using <c-combo-box-cell>.

It binds the typeAttributes.value, typeAttributes.options, row ID (rowKeyValue), and event handlers onchange and onclick, enabling the datatable’s custom ‘customCombo’ type for editable picklists.

  1. At last, expose the main LWC component to the lightning pages by using the code below in the meta.xml file inside the < LightningComponentBundle> tag.
<isExposed>true</isExposed>

    <targets>
        <target>lightning__AppPage</target>
        <target>lightning__RecordPage</target>
        <target>lightning__HomePage</target>
    </targets>
  1. After this, deploy the LWC component to the lightning page, and there you will picklist values in the dropdown, where we can edit and change the opportunity values.
How to add Picklist combo box in LWC data table

This way, we can display editable pikclist values in the Salesforce LWC data tables using the combo box feature.

Conclusion

In this Salesforce tutorial, we have learned how to add picklist field values to an LWC data table. In the above steps, we have added a picklist dropdown to each row by creating a custom customCombo type and using the lightning-combobox component. With this, we have successfully integrated editable picklist values such as the Industry field into an LWC data table.

You may also like to read:

Agentforce in Salesforce

DOWNLOAD FREE AGENTFORCE EBOOK

Start with AgentForce in Salesforce. Create your first agent and deploy to your Salesforce Org.

Salesforce flows complete guide

FREE SALESFORCE FLOW EBOOK

Learn how to work with flows in Salesforce with 5 different real time examples.