Picklist in LWC Datatable Inline Edit

by Rijwan Mohmmed
147 comments
picklist-in-lwc-datatable-inline-edit

Hello friends, today we are going to discuss How to set Picklist in LWC Datatable Inline Edit Salesforce. In LWC Datatable there are limited field types and the Picklist type is not there. But not to worry We will do this by creating a custom type Datatable and will create the Picklist type field.

Inline editing is a game-changer, and now, you can enhance it further with picklist fields. Editing picklist values directly within a Datatable boosts efficiency and user satisfaction.

Also, check this: Chain Wire methods in LWC

picklist-in-lwc-datatable-inline-edit-output-techdicer

Key Highlights :

  1. Create a Picklist type field in Datatable
  2. We can edit this field
  3. We can show/hide this picklist by the pen icon.
  4. Update the data.
  5. Picklist options fetch dynamically for LWC Datatable.
  6. Efficiency: No more navigating away to edit picklists. Users can update them instantly within the table.
  7. User Experience: Enhance user satisfaction by reducing the steps needed for data updates.
  8. Accuracy: Prevent errors by ensuring users select from valid picklist values.

🚀 Empower Your LWCs: By incorporating picklist inline editing in Datatables, you’re unlocking a smoother and more intuitive data management experience. Whether it’s managing leads, contacts, or any records with picklist fields, this feature raises your LWC development to the next level.

Give it a shot and see the transformation in your user interactions! 🌐🎉

Process & Code :

AccountDataController.cls :

public class AccountDataController {
    
    @AuraEnabled (cacheable=true)
    public static List<Account> fetchAccounts(){
        return [SELECT Id, Name, Type, Phone 
                FROM Account WHERE Type !='' LIMIT 10];       
    }
}

lWCCustomDatatableType.HTML : We create a custom type Datatable here which extends standard LWC Datatable. Also, create an extra HTML file picklistColumn.html, pickliststatic.html so we can put the Picklist Combobox and its static value here. Below image of the structure

<template>

</template>

picklistColumn.html :

<template>
		<lightning-combobox name="picklist" data-inputable="true" label={typeAttributes.label} value={editedValue} placeholder={typeAttributes.placeholder} options={typeAttributes.options} variant='label-hidden'
            dropdown-alignment="auto"></lightning-combobox>
</template>

pickliststatic.html :

<template>
    <span class="slds-truncate" title={value}>{value}</span>
</template>

lWCCustomDatatableType.JS:

import LightningDatatable from 'lightning/datatable';
import picklistColumn from './picklistColumn.html';
import pickliststatic from './pickliststatic.html'

export default class LWCCustomDatatableType extends LightningDatatable {
    static customTypes = {
        picklistColumn: {
            template: pickliststatic,
            editTemplate: picklistColumn,
            standardCellLayout: true,
            typeAttributes: ['label', 'placeholder', 'options', 'value', 'context', 'variant','name']
        }
    };
}

Now we will create the last final LWC component

lWCDatatableWithPicklist.html :

<template>
    <!-- header -->
    <div class="slds-tabs_card">
		<div class="slds-page-header">
			<div class="slds-page-header__row">
				<div class="slds-page-header__col-title">
					<div class="slds-media">
						<div class="slds-media__figure">
							<span class="slds-icon_container slds-icon-standard-opportunity">
								 <lightning-icon icon-name="standard:recipe" alternative-text="recipe" title="recipe"></lightning-icon>
                            </span>
						</div>
						<div class="slds-media__body">
							<div class="slds-page-header__name">
								<div class="slds-page-header__name-title">
									<h1>
										<span>PickList In LWC Inline Datatable Edit</span>
										<span class="slds-page-header__title slds-truncate" title="Recently Viewed">TechDicer</span>
									</h1>
								</div>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div> <br/>
    <!-- /header -->

    <!-- create folder card -->
    <lightning-card  variant="Narrow"  title="PickList In LWC Inline Datatable Edit" icon-name="standard:folder" class="cardSpinner">
        <!-- loader -->
        <div if:true={showSpinner}>
            <lightning-spinner
                alternative-text="Loading..." variant="brand">
            </lightning-spinner>
        </div>
        <!-----/loader-------->
        <div class="slds-var-p-around_small">
            <template if:true={data}>
                <c-l-w-c-custom-datatable-type
                    key-field="Id" 
                    data={data} 
                    columns={columns} 
                    onvalueselect={handleSelection}
                    draft-values={draftValues} 
                    oncellchange={handleCellChange}
                    onsave={handleSave}
                    oncancel={handleCancel}
                    hide-checkbox-column>
                </c-l-w-c-custom-datatable-type>
            </template>
        </div>
    </lightning-card>
</template>

lWCDatatableWithPicklist.JS:

import { LightningElement, track, wire } from 'lwc';
import fetchAccounts from '@salesforce/apex/AccountDataController.fetchAccounts';
import ACCOUNT_OBJECT from '@salesforce/schema/Account';
import TYPE_FIELD from '@salesforce/schema/Account.Type';
import { updateRecord } from 'lightning/uiRecordApi';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import { refreshApex } from '@salesforce/apex';
import { getPicklistValues, getObjectInfo } from 'lightning/uiObjectInfoApi';

const columns = [
    { label: 'Name', fieldName: 'Name', editable: true },
    { label: 'Phone', fieldName: 'Phone', type: 'phone', editable: true },
    {
        label: 'Type', fieldName: 'Type', type: 'picklistColumn', editable: true, typeAttributes: {
            placeholder: 'Choose Type', options: { fieldName: 'pickListOptions' }, 
            value: { fieldName: 'Type' }, // default value for picklist,
            context: { fieldName: 'Id' } // binding account Id with context variable to be returned back
        }
    }
]

export default class CustomDatatableDemo extends LightningElement {
    columns = columns;
    showSpinner = false;
    @track data = [];
    @track accountData;
    @track draftValues = [];
    lastSavedData = [];
    @track pickListOptions;

    @wire(getObjectInfo, { objectApiName: ACCOUNT_OBJECT })
    objectInfo;

    //fetch picklist options
    @wire(getPicklistValues, {
        recordTypeId: "$objectInfo.data.defaultRecordTypeId",
        fieldApiName: TYPE_FIELD
    })

    wirePickList({ error, data }) {
        if (data) {
            this.pickListOptions = data.values;
        } else if (error) {
            console.log(error);
        }
    }

    //here I pass picklist option so that this wire method call after above method
    @wire(fetchAccounts, { pickList: '$pickListOptions' })
    accountData(result) {
        this.accountData = result;
        if (result.data) {
            this.data = JSON.parse(JSON.stringify(result.data));

            this.data.forEach(ele => {
                ele.pickListOptions = this.pickListOptions;
            })

            this.lastSavedData = JSON.parse(JSON.stringify(this.data));

        } else if (result.error) {
            this.data = undefined;
        }
    };

    updateDataValues(updateItem) {
        let copyData = JSON.parse(JSON.stringify(this.data));

        copyData.forEach(item => {
            if (item.Id === updateItem.Id) {
                for (let field in updateItem) {
                    item[field] = updateItem[field];
                }
            }
        });

        //write changes back to original data
        this.data = [...copyData];
    }

    updateDraftValues(updateItem) {
        let draftValueChanged = false;
        let copyDraftValues = [...this.draftValues];
        //store changed value to do operations
        //on save. This will enable inline editing &
        //show standard cancel & save button
        copyDraftValues.forEach(item => {
            if (item.Id === updateItem.Id) {
                for (let field in updateItem) {
                    item[field] = updateItem[field];
                }
                draftValueChanged = true;
            }
        });

        if (draftValueChanged) {
            this.draftValues = [...copyDraftValues];
        } else {
            this.draftValues = [...copyDraftValues, updateItem];
        }
    }

    //handler to handle cell changes & update values in draft values
    handleCellChange(event) {
        //this.updateDraftValues(event.detail.draftValues[0]);
        let draftValues = event.detail.draftValues;
        draftValues.forEach(ele=>{
            this.updateDraftValues(ele);
        })
    }

    handleSave(event) {
        this.showSpinner = true;
        this.saveDraftValues = this.draftValues;

        const recordInputs = this.saveDraftValues.slice().map(draft => {
            const fields = Object.assign({}, draft);
            return { fields };
        });

        // Updateing the records using the UiRecordAPi
        const promises = recordInputs.map(recordInput => updateRecord(recordInput));
        Promise.all(promises).then(res => {
            this.showToast('Success', 'Records Updated Successfully!', 'success', 'dismissable');
            this.draftValues = [];
            return this.refresh();
        }).catch(error => {
            console.log(error);
            this.showToast('Error', 'An Error Occured!!', 'error', 'dismissable');
        }).finally(() => {
            this.draftValues = [];
            this.showSpinner = false;
        });
    }

    handleCancel(event) {
        //remove draftValues & revert data changes
        this.data = JSON.parse(JSON.stringify(this.lastSavedData));
        this.draftValues = [];
    }

    showToast(title, message, variant, mode) {
        const evt = new ShowToastEvent({
            title: title,
            message: message,
            variant: variant,
            mode: mode
        });
        this.dispatchEvent(evt);
    }

    // This function is used to refresh the table once data updated
    async refresh() {
        await refreshApex(this.accountData);
    }
}

lWCDatatableWithPicklist.css :

.cardSpinner{
    position: relative;;
}

Output :

picklist-in-lwc-datatableinline-edit-output-techdicer

Reference :

  1. LWC Datatable
  2. Inline Editing in lightning-datatable in LWC Salesforce
What’s your Reaction?
+1
9
+1
1
+1
2
+1
2
+1
14
+1
2

You may also like

147 comments

Mohsina October 20, 2022 - 5:33 am

Hii Rijwan the dropdown is not opening like that for me ,even when I used the same code.Can you please help

Reply
Rijwan Mohmmed October 23, 2022 - 5:46 am

Can you please share your file structure.

Reply
Marwan October 27, 2022 - 9:09 am

Hi Rijwan the dropdown works perfect for me when i put de LWC in a tab but it doesn’t when I put it on a record page, do you know why? Thank you!!

Reply
Rijwan Mohmmed October 28, 2022 - 3:47 pm

Can you please share a screen shot or video link.

Reply
Rijwan Mohmmed November 1, 2022 - 4:01 am

Also, check the position of the dropdown list.

Reply
Rijwan Mohmmed November 1, 2022 - 4:57 am

I have updated the CSS file which is the static resource LWCDatatablePicklist. Can you please check now.

Reply
Christian October 31, 2022 - 8:41 am

Hi Rijwan,
first thank for this code :). I have an error when i try to save new picklist value i receive
‘Field Type does not exist ‘

lwc002_EditInvoice.js:1 {Id: ‘a16Aa0000000PCxIAM’, Type: ‘Commit’}
t @ aura_prod.js:1
lwc002_EditInvoice.js:1 {status: 400, body: {…}, headers: {…}, ok: false, statusText: ‘Bad Request’, …}body: {message: ‘Field Type does not exist.’, statusCode: 400, errorCode: ‘POST_BODY_PARSE_ERROR’}errorType: “fetchResponse”headers: {}ok: falsestatus: 400statusText: “Bad Request”[[Prototype]]: Object

Could you help me

Reply
Rijwan Mohmmed November 1, 2022 - 3:24 am

check getPicklistValues , I think you are putting field which is not there in Org

Reply
Hassan November 2, 2022 - 5:02 pm

I tried your code, but options are undefined in the pickerColumn. I have checked wire is working correctly.

here is the column object
{
label: ‘Day Part’, fieldName: ‘label’, type: ‘picklistColumn’, editable: false, typeAttributes: {
placeholder: ‘Choose Type’,
options: { fieldName: ‘pickListOptions’ },
value: { fieldName: ‘label’ }, // default value for picklist,
context: { fieldName: ‘index’ } // binding account Id with context variable to be returned back
}
}

Reply
Rijwan Mohmmed November 3, 2022 - 12:54 pm

pickListOptions is getting values or not in JS

Reply
Oleh November 7, 2022 - 7:15 pm

Hi Rijwan. Thank you! Your code works perfectly for me. Data in all columns are edited and saved correctly. Except for picklist column. When I edit the picklist value, it doesn’t save(An error occured!!). What could be wrong?

Reply
Rijwan Mohmmed November 9, 2022 - 5:44 pm

What was the error?

Reply
Rijwan Mohmmed November 11, 2022 - 10:26 am

Can you please check Line no 108 in CustomDatatableDemo.JS

Reply
Oleh November 14, 2022 - 7:21 pm

When I change the picklist value and tried to save it, I got the nest error:
“Error! An error ocurred!!”.

Reply
Oleh November 17, 2022 - 4:49 am

You’re right. Thank you!

Reply
Duong November 18, 2022 - 10:18 am

can you show multi inline picklist with checked box?

Reply
Rijwan Mohmmed November 18, 2022 - 3:27 pm

yes we can use multi-select picklist.

Reply
Android November 30, 2022 - 11:53 am

data table save and cancel button at the bottom of datatable is not getting open when we change the value in combo box

Reply
Rijwan Mohmmed December 1, 2022 - 4:21 pm

Can you please send me a screenshot, As per my understanding it is working fine. If you have time I will post a new blog regarding this in simple steps at the end of this week.

Reply
saloni December 2, 2022 - 5:42 am

Hi Rijwan,

I able to load datatable but while clicking on picklist, Type picklist values is not loading.

Reply
Rijwan Mohmmed December 2, 2022 - 6:32 am

Hi Saloni,
please check below code and check console
//fetch picklist options
@wire(getPicklistValues, {
recordTypeId: “$objectInfo.data.defaultRecordTypeId”,
fieldApiName: TYPE_FIELD
})

wirePickList({ error, data }) {
if (data) {
this.pickListOptions = data.values;
} else if (error) {
console.log(error);
}
}

Reply
MOHIT CHAUHAN December 8, 2022 - 1:26 pm

HI,
I want to use picklist for multiple columns.
Can you suggest how I can set picklistOptions for different columns.

Reply
Rijwan Mohmmed December 9, 2022 - 3:47 am

Hi MOHIT CHAUHAN
Just create other one only field type should be type: ‘picklistColumn’

Reply
MOHIT CHAUHAN December 9, 2022 - 5:37 am

I am unable to show different values in options for different picklist, because I am fetching columns dynamically from apex method with the help of metadata using field sets.

Reply
MOHIT CHAUHAN December 9, 2022 - 6:22 am

picklistColumns=YEAR_FIELD;
@wire (getMarketingPlanColumns, {currentMarketingPlanCountry: ‘$Country’})
marketingPlanColumns(result) {
if(result.data) {
this.columns = JSON.parse(JSON.stringify(result.data));
this.columns.push({
type: ‘action’,
typeAttributes:{rowActions: action}
});
this.columns.forEach(column => {
if(column.type == “PICKLIST”){
// @wire(getPicklistValues, {recordTypeId: ‘$recordTypeId’, fieldApiName: COUNTRY_FIELD})
// wirePickList({ error, data }) {
// if (data) {
// this.pickListOptions = data.values;
// console.log(this.pickListOptions);
// } else if (error) {
// console.log(‘error ‘+error);
// }
// };

column.typeAttributes = {
placeholder: ‘Choose Type’,
options: { fieldName: ‘pickListOptions’ },
value: { fieldName: ‘column.fieldName’ }, // default value for picklist,
context: { fieldName: ‘Id’ } // binding account Id with context variable to be returned back
}
}
})
// console.log(this.columns);
}
};

Reply
Rijwan Mohmmed December 9, 2022 - 2:39 pm

The issue in your JSON put type: ‘picklistColumn’ on columns where you want to the picklist. This is possible.

Isha April 15, 2023 - 1:46 am

Hi Rijwan,
I am not getting where you mentioned ‘Just create other one only field type should be type: ‘picklistColumn’’ Can you please provide more detail on this one. I am able to get one picklist only, for other it is blank, even though wire method to get picklist has values.

Reply
Rijwan Mohmmed April 17, 2023 - 5:53 am

@Isha, Please setup a meeting by click book a meeting button on my website in right side

Reply
Balaji December 16, 2022 - 7:53 am

Hi Rijan

Not able to get picklist value in UI but it showing correcly in console.log

Reply
Balaji December 16, 2022 - 7:57 am

const columns = [
{ label: ‘Claim ID’, fieldName: ‘ClaimID__c’ },
{ label: ‘Member Name’, fieldName: ‘MH_MemberName__c’, type: ‘text’ },
{ label: ‘DOS From’, fieldName: ‘MH_DOSFrom__c’, type: ‘text’ },
{ label: ‘DOS To’, fieldName: ‘MH_DOSTo__c’, type: ‘text’ },
{ label: ‘Status’, fieldName: ‘MH_Status__c’, type: ‘text’ },
{label: ‘Denial Reason’, fieldName: ‘MH_Denial_Reason__c’, type: ‘picklistColumn’, editable: true, typeAttributes: {
placeholder: ‘Choose Type’, options: { fieldName: ‘pickListOptions’ },
value: { fieldName: ‘MH_Denial_Reason__c’ }, // default value for picklist,
context: { fieldName: ‘Id’ } // binding account Id with context variable to be returned back
}
}
];

export default class BasicDatatable extends LightningElement {
@api recordId;
@track recdata;
columns = columns;
@track pickListOptions;
draftValues = [];

@wire(getObjectInfo, { objectApiName: CASE_CLAIM })
objectInfo;

@wire(getPicklistValues, {recordTypeId: ‘$objectInfo.data.defaultRecordTypeId’,fieldApiName: DENIAL_REASON })
getdenialreason({ error, data }) {
if (data) {
console.log(‘datapick’);
console.log(data);
this.pickListOptions = data.values;
console.log(‘this.pickListOptions’);
console.log(JSON.stringify(this.pickListOptions));

} else if (error) {
console.log(‘pickListOptionserror’);
console.log(error);
}
}

Reply
Rijwan Mohmmed December 16, 2022 - 12:30 pm

Hi @Balaji,
Have you tried my code with type picklist

Reply
Balaji December 16, 2022 - 2:18 pm

Yes but I have used your code LWCCustomDatatable and parent component is different

import { LightningElement,api,wire,track } from ‘lwc’;
import getdenialcashclaim from ‘@salesforce/apex/mh_caseclaimcontroller.getcashclaim’;
import { updateRecord } from ‘lightning/uiRecordApi’;
import { ShowToastEvent } from ‘lightning/platformShowToastEvent’;
import { refreshApex } from ‘@salesforce/apex’;
import { getPicklistValues, getObjectInfo } from ‘lightning/uiObjectInfoApi’;
import CASE_CLAIM from ‘@salesforce/schema/MH_CaseClaims__c’;
import DENIAL_REASON from ‘@salesforce/schema/MH_CaseClaims__c.MH_Denial_Reason__c’;
//import pickListValueDynamically from ‘@salesforce/apex/mh_caseclaimcontroller.pickListValueDynamically’;

const columns = [
{ label: ‘Claim ID’, fieldName: ‘ClaimID__c’ },
{ label: ‘Member Name’, fieldName: ‘MH_MemberName__c’, type: ‘text’ },
{ label: ‘DOS From’, fieldName: ‘MH_DOSFrom__c’, type: ‘text’ },
{ label: ‘DOS To’, fieldName: ‘MH_DOSTo__c’, type: ‘text’ },
{ label: ‘Status’, fieldName: ‘MH_Status__c’, type: ‘text’ },
{
label: ‘Denial Reason’, fieldName: ‘MH_Denial_Reason__c’, type: ‘picklistColumn’, editable: true, typeAttributes: {
label:{fieldName: ‘pickListOptions’},
placeholder: ‘Select Reason’, options: { fieldName: ‘pickListOptions’ },
value: { fieldName: ‘MH_Denial_Reason__c’ }, // default value for picklist,
context: { fieldName: ‘Id’ } // binding account Id with context variable to be returned back
}
}
];

export default class BasicDatatable extends LightningElement {
@api recordId;
@track recdata;
columns = columns;
@track pickListOptions;
draftValues = [];

@wire(getObjectInfo, { objectApiName: CASE_CLAIM })
objectInfo;

@wire(getPicklistValues, {recordTypeId: ‘$objectInfo.data.defaultRecordTypeId’,fieldApiName: DENIAL_REASON })
getdenialreason({ error, data }) {
if (data) {
console.log(‘datapick’);
console.log(data);
this.pickListOptions = data.values;
console.log(‘this.pickListOptions’);
console.log(JSON.stringify(this.pickListOptions));

} else if (error) {
console.log(‘pickListOptionserror’);
console.log(error);
}
}

/* @wire(pickListValueDynamically, {customObjInfo: {‘sobjectType’ : ‘MH_CaseClaims__c’},
selectPicklistApi: ‘MH_Denial_Reason__c’})
getdenialreason({ error, data }) {
if (data) {
console.log(‘this.pickListOptions’);
console.log(data);
this.pickListOptions = data;

} else if (error) {
console.log(‘pickListOptionserror’);
console.log(error);
}
};*/

@wire(getdenialcashclaim,{recordId:’$recordId’})
getclaimrecord({error, data}){
if(data){
console.log(‘data’);
console.log(data);

this.recdata = data;
this.error = undefined;
}else{
console.log(‘error’);
this.error = error;
this.recdata = undefined;
}
}

}

*********************************************

Reply
Rijwan Mohmmed December 16, 2022 - 3:58 pm

Hi @Balaji, I think you missed something, Can you please check you HTML part .

Reply
Shiam Singh Rawat December 19, 2022 - 6:54 am

Hi Rijwan,
getting this error -> Invalid reference Order.Fsys_BillingType__c of type sobjectField in file fsys_PendingBillingReport.js: Source

Does your functionality work on custom fields??? I am getting this error on this line-> import OWNER_FIELD from ‘@salesforce/schema/Order.Fsys_BillingType__c’;
I was writing the code on Lightning studio(beta)

Reply
Rijwan Mohmmed December 19, 2022 - 11:47 am

HI Shiam Singh Rawat, This also work for custom objects

Reply
Rijwan Mohmmed December 19, 2022 - 11:48 am

Issue in Lightning studio(beta), you have to checked the checkbox in bottom one then deploy it will works

Reply
Jim December 30, 2022 - 5:20 pm

Hi Rijwan,

Thank you so much for paving the way here. I’ve tried to use your strategy in my component, but I’m getting an error in the console when I click on the pencil icon to edit the picklist field. “Cannot read properties of null (reading ‘value’).

And there is also another error: Editable custom types must define an editTemplate that includes an element with attribute data-inputable set to “true”.

Not sure if the two errors are related. I’ve checked my picklistColumn.html and it definitely has data-inputable=”true” as a property.

Any ideas?

Reply
Rijwan Mohmmed January 2, 2023 - 6:49 am

Hi @Jim,
Did you check all components deployed properly

Reply
Gopal January 5, 2023 - 11:36 am

Hi Rijwan
Can you tell me How to add upload file button in data table & how to add three picklist in single data table. Out of these three picklist one picklist is dependent picklist.

Reply
Rijwan Mohmmed January 5, 2023 - 12:03 pm

Hi Gopal, the upload file button can be added like row action add in LWC data table.
also, multiple picklists can be added but dependent picklists, no idea about this.

Reply
Gopal January 5, 2023 - 1:52 pm

Thank you Rijwan

Reply
Kari SaiMohan February 1, 2023 - 2:22 am

missing root template tag error in picklistColumn.html

Reply
Rijwan Mohmmed February 1, 2023 - 3:52 pm

check all components code again.

Reply
Shallet Antony February 6, 2023 - 10:52 am

hi Rijwan,

Sorry I am new LWC so can you confrim me are we creating two LWCs here right?
Bcoz I am confused with your file structure,

Thank you
Shallet

Reply
Rijwan Mohmmed February 6, 2023 - 12:45 pm

yupp

Reply
Shallet Antony February 7, 2023 - 6:35 pm

Thank you so much!. I have done it but I am not able to see the picklist values in the list. can you help me?

Reply
Kari SaiMohan February 10, 2023 - 8:22 am

how to filter the child records in above code can you please modify that

Reply
Rijwan Mohmmed February 10, 2023 - 8:59 am

@Kari please check this link for filter data
https://techdicer.com/filter-search-in-lwc-lightning-datatable/

Reply
Sumanta Satpathy February 11, 2023 - 1:05 pm

Hi Rijwan,

I asked for a call. But you did not join. Please let me know what is the best time to do so. I need your help.

Reply
Rijwan Mohmmed February 11, 2023 - 2:01 pm

Can you please arrange one more meeting today? Sorry I missed this

Reply
Sumanta Satpathy February 11, 2023 - 2:40 pm

Hi Rijwan,

I have sent another invite for tomorrow. Please have a look.

Reply
Sai February 13, 2023 - 7:24 am

Hi Rijwan,
How to fetch different two picklist fields with different values ?

Ex : Field A has values Yes, No
Field B has values Right, Wrong

On UI , its rendering Yes, No for both picklist fields. What did I miss here ? Could you please advise ?

Reply
Sai February 13, 2023 - 9:11 am

Hi Rijwan,
Can we connect today at 5pm for quick call? Unable to fetch picklist fields with different values. Please assist.

Thank you!

Sai Mohan

Reply
Rijwan Mohmmed February 13, 2023 - 9:47 am

Hi @Sai, Please schedule meeting by click this button in right side of my website >>Book Meeting For Free

Reply
Sai Mohan February 13, 2023 - 5:17 pm

Thanks Rijwan you solved last 2 weeks issue thank you so much Great

Reply
chandrabhan February 21, 2023 - 2:55 pm

@Rijwan
Can you help me for multi select picklist

Reply
Rijwan Mohmmed February 21, 2023 - 6:46 pm

Let me first check for multi-select picklist

Reply
Srikanth February 24, 2023 - 1:41 pm

Hi Rizwan I had some confusion can you send me entire code and how many components we need to build to get this ui please let me know and pls send the whole code I had some requirements in my project

Reply
Rijwan Mohmmed February 24, 2023 - 3:47 pm

There are two components only.

Reply
jayesh kharche March 1, 2023 - 2:03 pm

Hi @Rizwan,
will it work for more than one picklist field like ‘type’ and ‘industry’ picklist field in datatable?

Reply
Rijwan Mohmmed March 1, 2023 - 2:08 pm

Yupp , it will work for multiple Picklists

Reply
neon March 7, 2023 - 12:35 pm

Hi, Thanks for the article.
I am facing a problem How can I add params in the @wire?
I’ve changed the apex this way.
public static List fetchAccounts(Id scheduledClassId)
Now how can I add an extra param in the wire?
@wire(fetchAccounts, {pickList: ‘$pickListOptions’ })

Reply
Rijwan Mohmmed March 7, 2023 - 12:37 pm

@wire(fetchAccounts, {scheduledClassId : ‘test’, pickList: ‘$pickListOptions’ })

Reply
Shallet Antony March 22, 2023 - 1:34 pm

hi Rijwan,

I am getting below message intermittently ….can you help me please?

message
:
“An error occurred while trying to update the record. Please try again.”
output
:
errors
:
Array(1)
0
:
{constituentField: null, duplicateRecordError: null, errorCode: ‘UNABLE_TO_LOCK_ROW’, field: null, fieldLabel: null, …}

Thank you

Reply
Rajat Batheja April 11, 2023 - 11:23 am

Hi Rizwan, I am getting an Error While Saving the Record

Reply
Rijwan Mohmmed April 12, 2023 - 4:19 am

Can you please share the error

Reply
Aahna Singh April 12, 2023 - 9:05 pm

The picklist shows the API name, how to show the label for it?

Reply
Rijwan Mohmmed April 13, 2023 - 4:14 am

Hi @aahna Singh
In picklistColumn.html file
I used variant=’label-hidden’ in combobox so If you want to show label remove this variant.

Reply
AAHNA SINGH April 13, 2023 - 5:35 am

hi, tried that. Did not work, still shows the API name of the picklist values on the datatable.

Reply
AAHNA SINGH April 13, 2023 - 5:43 am

What about pickliststatic.html? Any changes need to be made there?

Reply
Rijwan Mohmmed April 14, 2023 - 5:18 pm

Please setup a meeting by click book a meeting button on my website in right side

Reply
AAHNA SINGH April 25, 2023 - 4:36 pm

I requested a call. But you did not join. Please let me know what is the best time to do so.

Rijwan Mohmmed April 27, 2023 - 12:50 pm

I am sorry for the inconvenience. You can schedule the call on sunday

Aahna Singh April 30, 2023 - 6:43 am

I scheduled a call for Sunday at 12 PM for your convenience, but you didn’t participate in that one either. Please let me know a time and date that work for you.

Rijwan Mohmmed April 30, 2023 - 11:29 am

I already reschedule it

Anny June 8, 2023 - 1:58 pm

“I have the same question. How can I deal with it?

Reply
Rajeswari April 19, 2023 - 10:50 am

Hi Rizwan, can you post this scenario-related code?
custom LWC picklist component with a search option as in the Standard Salesforce.
Pass the object that exists in the org & on selecting any object from the dropdown, display the records in the table with the inline edit option.

Reply
Rijwan Mohmmed April 19, 2023 - 5:19 pm

Hi @Rajeswari, I can but it will take some time.

Reply
oumaima April 20, 2023 - 10:16 am

hello i have declared my column like this : {
label: ‘Résiliation’, fieldName: ‘Resiliation__c’, type: ‘picklistColumn’, editable: true, typeAttributes: {
placeholder: ”, options: { fieldName: ‘pickListOptions’ },
value: { fieldName: ‘Resiliation__c’ }, // default value for picklist,
context: { fieldName: ‘Id’ } // binding account Id with context variable to be returned back
}
}
And for the options ;
@wire(getObjectInfo, { objectApiName: DOSSIER_REVALO_OBJECT })
objectInfo;

//fetch picklist options
@wire(getPicklistValues, {
recordTypeId: “$objectInfo.data.defaultRecordTypeId”,
fieldApiName: RESILIATION_FIELD
})
wirePickList({ error, data }) {
if (data) {
this.pickListOptions = data.values;
} else if (error) {
console.log(error);
}
console.log(this.pickListOptions);
} ant the console log returuns value but in the front i get blank options

Reply
Rijwan Mohmmed April 21, 2023 - 12:24 pm

Check line number 55 in my JS code.

Reply
Vishu April 27, 2023 - 8:57 am

Hey Rijwan,
What to do if I want to reduce my picklist column size I am decreasing the size of lightning combo-box but its only decreasing leaving a blank space behind it. How to decrease the size of whole component (here the whole picklist)

Reply
Rijwan Mohmmed April 27, 2023 - 12:53 pm

Schedule a call on sunday

Reply
Vlad May 10, 2023 - 8:26 pm

Upon fetching picklist values it automatically transformed array to object
I don`t know why did it do it
In wire:
[{“label”:”Hot”,”value”:”Hot”},{“label”:”Warm”,”value”:”Warm”},{“label”:”Cold”,”value”:”Cold”}]
In picklist template
{“0”:{“label”:”Hot”,”value”:”Hot”},”1″:{“label”:”Warm”,”value”:”Warm”},”2″:{“label”:”Cold”,”value”:”Cold”}}

Reply
Rijwan Mohmmed May 11, 2023 - 4:43 am

Please check the code , may be you are doing casting.
Let me know If you want We can connect on call on click Book a meeting on my website.

Reply
Meredith Pearson May 18, 2023 - 4:04 pm

Hello, my datatable is working great except one of my picklist values has a special character ‘N/A’. The values show correctly upon selecting N/A but once saved it saves it as the api value of ‘n_a’. How can I update to have it save as the label value?

Reply
Rijwan Mohmmed May 22, 2023 - 2:54 pm

You can book a meeting on my website

Reply
Arun P May 30, 2023 - 3:36 am

Hello Rijwan, I have implemented the above code.
Now when i click edit, It loading as a picklist but its only showing the placeholder not the entire picklist options.
Also i have passed the picklist option from Apex using schema instead of getting in LWC. Here a JSON format for the same.

“typeAttributes”: {
“editable”: true,
“objectApiName”: “CCM_Master”,
“fieldApiName”: “CCM_Business_Code__c”,
“placeholder”: “Select an option”,
“options”: [
{“label”: “CFR”, “value”: “CFR”},
{“label”: “CIF”, “value”: “CIF”},
{“label”: “CIP”, “value”: “CIP”},
{“label”: “CPT”, “value”: “CPT”},
{“label”: “DAP”, “value”: “DAP”},
{“label”: “DDP”, “value”: “DDP”},
{“label”: “DPU”, “value”: “DPU”},
{“label”: “FAS”, “value”: “FAS”},
{“label”: “FCA”, “value”: “FCA”},
{“label”: “FOB”, “value”: “FOB”}
]
}

Reply
Rijwan Mohmmed May 30, 2023 - 2:28 pm

Can you please check console log

Reply
Arun P June 4, 2023 - 7:21 am

Hello Rijwan, when check console log using debug mode i am not getting any error.

Can we check of the options value has been passed to child from parent or not? As the placeholder value is passing but not the options when click edit.
This is how i am getting the value in my parent component.
connectedCallback() {
loadStyle(this, modal);
console.log(‘Id: ‘ + this.RecordId);

getdata({ recordId: this.RecordId})
.then((response) => {
if (response) {
console.log(response);
this.tables = response.map((table) => ({
id: table.id,
name: table.name,
data: table.dataList ? table.dataList.map((record) => ({
…record,
deleteRow: ‘Delete’,
isNew: false,
})) : [],
columns: table.columns.map((column) => {
if (column.type === ‘picklistColumn’) {
return {
…column,
type: ‘picklistColumn’,
editable: true,
typeAttributes: {
editable: true,
objectApiName: ‘CCM_Business_Code__c’,
fieldApiName: column.fieldName,
placeholder: ‘Select an option’,
options: column.picklistOptions.map((option) => ({
label: option,
value: option,
})),
},
};
} else {
return {
…column,
editable: true,
};
}
}),
draftValues: [],
}));
console.log(‘tables’ + this.tables);
console.log(‘Agr’ + JSON.stringify(this.tables));
}
})
.catch((error) => {
console.error(‘Error retrieving data’, error);
})
.finally(() => {
this.isLoading = false;
});
}

And on the HTML Side

>

Reply
Arun P June 4, 2023 - 5:59 pm

Hello Rijwan, i just tried something, look like it issue with inline edit. When i click the inline edit option, It not rendering the dropdown.

When i assigned “template: picklistColumn” During the initial load it getting all the picklist options. Any reason why it is happening ?

static customTypes = {
picklistColumn: {
template: picklistColumn,
editTemplate: picklistColumn,
standardCellLayout: true,
typeAttributes: [‘label’, ‘placeholder’, ‘options’, ‘value’, ‘context’, ‘variant’, ‘name’]
}
};

Reply
V March 14, 2024 - 7:31 pm

I have the same issue:
When i click the inline edit option, It not rendering the dropdown.

When i assigned “template: picklistColumn” During the initial load it getting all the picklist options.

How did you solve this?

Rijwan Mohmmed March 15, 2024 - 6:41 am

Please book a meeting I can help you

Arun P June 4, 2023 - 7:23 am

The this is how i have defined on HTML Side:

>

Reply
Arun P June 4, 2023 - 8:03 am

>

Reply
Nagaratna June 8, 2023 - 9:49 am

Hi Rijwan, what about multi picklist.

Reply
Huseyin July 13, 2023 - 7:41 pm

Could you find any solution for multi-picklist?

Reply
Naoki June 14, 2023 - 2:22 am

Thank you for your help.
The reference code seems to work as expected.
I hope this information helps many people.
There is a package called List Editor that can do something very similar.
(https://appexchange.salesforce.com/appxListingDetail?listingId=a0N3u00000PFXi6EAH&tab=r)
However, List Editor has two disadvantages: I would appreciate it if you could point me to some code that can solve it someday.
・When batch editing with the pencil mark on the upper right, numeric keypad input is not accepted for currency type.
・When batch editing with the pencil mark on the upper right, after searching for the reference item, you can not select the item without clicking with the mouse.

Reply
Joscelyn Stonis June 14, 2023 - 1:45 pm

Hello,
How do i do this for multiple picklist fields? I need to add another one.

Thanks,
Joscelyn

Reply
Rijwan Mohmmed June 15, 2023 - 4:04 am

This is only for Single select Picklist.

Reply
Joscelyn Stonis June 14, 2023 - 1:59 pm

Rijwan,
I need to know how to pass multiple picklists in this wire function call:

//here I pass picklist option so that this wire method call after above method
@wire(fetchAttendees, { pickList: ‘$pickListOptions’, id: ‘$recordId’})
attendeeData(result) {

Do I add another param pickList2? I tried booking meeting but it won’t let me.

Reply
DJ June 26, 2023 - 2:31 pm

Tried replicating your code in my developer org, the table renders as expected but picklist values do not render when I click the inline-edit. In the console log, the ‘pickListOptions’ variable was populated after the @wire render.

Reply
Rijwan Mohmmed June 26, 2023 - 2:34 pm

Hi DJ, did you copy full code because I also passing picklistoption in next wire method so it will call after this (chaining wire method)

Reply
DJ June 26, 2023 - 2:49 pm

I used below code to get dynamic picklist values

import { LightningElement, wire} from ‘lwc’;
import { getPicklistValues, getObjectInfo } from ‘lightning/uiObjectInfoApi’;
import TMT_OBJECT from ‘@salesforce/schema/Account’;
import TMTTYPE_FIELD from ‘@salesforce/schema/Account.Type’;

const columns = [
{ label: ‘Name’, fieldName: ‘Name’, editable: true },
{ label: ‘Phone’, fieldName: ‘Phone’, type: ‘phone’, editable: true },
{
label: ‘Type’, fieldName: ‘Type’, type: ‘picklistColumn’, editable: true, typeAttributes: {
placeholder: ‘Choose Type’, options: { fieldName: ‘pickListOptions’ },
value: { fieldName: ” }, // default value for picklist,
//context: { fieldName: ‘Id’ } // binding account Id with context variable to be returned back
}
}
]

export default class TestLwcDataTable extends LightningElement {
pickListOptions = [];
data = [{Name: ‘UserA’, Phone: ‘12345’, Type:”}];
columns = columns;
@wire(getObjectInfo, { objectApiName: TMT_OBJECT })objectInfo;
@wire(getPicklistValues, {
recordTypeId: ‘$objectInfo.data.defaultRecordTypeId’,
fieldApiName: TMTTYPE_FIELD
})wirePickList({ error, data }) {
if (data) {
console.log(‘data===>’,data);
const dataVal = Object.values(data.values);
console.log(‘pickList===>’,dataVal);
this.pickListOptions = dataVal;
console.log(‘pickListOptions===>’,this.pickListOptions);
} else if (error) {
console.log(error);
}
}
}

Reply
Joscelyn Stonis June 29, 2023 - 1:21 pm

Did you see my comment?

Rijwan,
I need to know how to pass multiple picklists in this wire function call:

//here I pass picklist option so that this wire method call after above method
@wire(fetchAttendees, { pickList: ‘$pickListOptions’, id: ‘$recordId’})
attendeeData(result) {

Do I add another param pickList2? I tried booking meeting but it won’t let me.

Reply
Joscelyn Stonis June 29, 2023 - 1:22 pm

Can you add another picklist?

If so, how do I do it?

Reply
Rijwan Mohmmed June 30, 2023 - 6:39 am

HI @Joscelyn
please book a meeting on below link
I can help you on call
https://topmate.io/rijwan_mohmmed

Reply
Huseyin July 13, 2023 - 7:37 pm

Hi Rijwan,

Is it possible to manage multi select picklist in LWC Datatable?

Reply
Rijwan Mohmmed July 14, 2023 - 5:20 am

Hi Huseyin,
I will try this today.

Reply
Huseyin July 13, 2023 - 7:42 pm

Could you find any solution for multi-picklist?

Reply
Joscelyn Stonis July 19, 2023 - 1:02 pm

Hi, me again. We had a discussion last week and you helped me add a second picklist. Is there a way to make it a dependent picklist in the datatable?

Thanks,
Joscelyn

Reply
Rijwan Mohmmed July 20, 2023 - 2:55 pm

Hi @Joscelyn Stonis
It may be possible but it will be very complex

Reply
SS August 8, 2023 - 6:00 am

hey how can we add two custom picklist in same datatable

Reply
Rijwan Mohmmed August 8, 2023 - 6:02 am

We can add. Please schedule a meeting by click book a meeting

Reply
ravi August 9, 2023 - 6:45 am

How to show pencil icon always to the right side of column

Reply
ravi August 14, 2023 - 12:36 pm

How to show pencil icon always to the right side of column, don’t want to show on hover only

Reply
Bibhu August 25, 2023 - 10:07 am

Hi , Can we make a pick list field mandatory?

Reply
Rijwan Mohmmed August 25, 2023 - 10:09 am

Yes we can make this.

Reply
salesforcelearner September 6, 2023 - 6:02 pm

Thanks for the blog. I m trying the snippet code I m facing issues related to save button there is a slight change in my design. I used the component in flow and flow binds the tabledata. after click save I m unable to refresh the tabledata. Can you suggest any other alternative how to refresh the table data. In my case wire refresh method may not work as table data passed as api property from flow.

Reply
Rijwan Mohmmed September 6, 2023 - 6:46 pm

You can imperative apex class method for get data in datatable

Reply
SS October 24, 2023 - 3:23 pm

Hi Rijwan,
I am using your code with a custom object and custom field but I am not getting the values in the combobox in the datatable, values are coming perfectly in the logs. Let me know if it is possible for you to connect. Thank you

Reply
Rijwan Mohmmed October 24, 2023 - 3:35 pm

Hi SS, Please schedule a meeting by click below link
https://topmate.io/rijwan_mohmmed

Reply
Luis October 29, 2023 - 7:21 pm

Hello Rizwan, I would like to thank you, it worked perfectly for my needs mainly because with this logic, I can mark multiple rows and replicate them instantly as if it were a standard column. I’m new and I ended up learning more because I didn’t know what dynamic and reactive variables were and I learned it by trying to find out the reason for the comment on line 48. I really liked your work.
Thank you again!

Reply
Rijwan Mohmmed October 30, 2023 - 4:02 am Reply
theo November 14, 2023 - 9:04 am

hi rijiwan, can this code runs on denpendent picklist values? i’ve tried but it seemed now working, thank u!

Reply
Rijwan Mohmmed November 14, 2023 - 2:50 pm

Hi @theo, I don’t think so, But I will post a blog on this as soon as possible

Reply
Shiha November 16, 2023 - 7:00 am

Hi, Thank you for the code. But the picklist always hides and i have to scroll to see the values.
Is there any way to display the picklist above the lwc?

Reply
Sayan December 21, 2023 - 1:27 pm

Hi Rizwan, I am getting everything correct except the picklist options are not coming up. Please help. I have populate the picklist attributes in the incoming results from apex and it is working correctly. But when clicking on the drop down nothing comes.

Reply
Rijwan Mohmmed December 24, 2023 - 1:42 pm

Can you please schedule a booking of meeting so I can resolve your issue. Booking button already there on my website .

Reply
Juan Manuel December 21, 2023 - 2:41 pm

If I wanted to be able to feed the picklist with fixed options, I tried this:

@track pickListOptions = [
{ label: ‘Option 1’, value: ‘1’ },
{ label: ‘Option 2’, value: ‘2’ },
{ label: ‘Option 3’, value: ‘3’ }
];

But it does not work. Does anyone know how I should make it work? I’m new to Salesforce

Reply
Rijwan Mohmmed December 24, 2023 - 1:43 pm

Hi Juan,
Can you please schedule a booking of meeting so I can resolve your issue. Booking button already there on my website .

Reply
Shantanu Sharma January 6, 2024 - 7:46 am

Hi Rijwan

Thanks for the blog, I tired using the same however, the picklist values are not visible over UI, they came is white card blocks(which matches the number of picklist options) when I open the drop down.(Console get the value of picklist options).
I tired to connect with you on 6th Jan 24 at 1PM but you didn’t joined.
Could you please help me on this.

Reply
Priyanka January 11, 2024 - 8:51 am

Hi Rijwan,
How to fetch different two picklist fields with different values ?

Ex : Field A has values Yes, No
Field B has values Right, Wrong

On UI , its rendering Yes, No for both picklist fields. What did I miss here ? Could you please advise ?

Reply
Rijwan Mohmmed January 11, 2024 - 10:38 am

Hi @Priyanka,
Can you please schedule a booking for meeting for your issue
https://topmate.io/rijwan_mohmmed

Reply
Shivam Tripathi January 16, 2024 - 12:44 pm

Hey Rijwan, I tried your code not getting the save and cancel button on edit of picklist values. Could you please help me out what could be the possible reason for this.

Reply
Rijwan Mohmmed January 16, 2024 - 5:49 pm

Hi @Shivam
Can you please schedule a booking for meeting for your issue
https://topmate.io/rijwan_mohmmed

Reply
Chaya March 26, 2024 - 11:05 am

HI Rijwan ,
This code works fine for me for one column picklist fields.
How to make this work for 10 columns ?
Please advice

Reply
Rijwan Mohmmed March 26, 2024 - 5:00 pm

Hi Chaya, Can you please explain this more

Reply
Chaya March 27, 2024 - 4:29 am

Picklist options are visible if we have one field with picklist datatype as per the code you have provided.
I have a requirement to work on 10 picklist field from account object.
I added the same code replicated for 1 more field.
But same picklist option is displaying for both fields.
Could you please suggest how to fix this issue ?

Reply
Rijwan Mohmmed March 27, 2024 - 6:21 am

book a meeting https://topmate.io/rijwan_mohmmed, I will help you

Reply
Phuc June 4, 2024 - 5:36 pm

Hello
ele.pickListOptions = this.pickListOptions;
in this snippet, ele.pickListOptions is never populated eventhough I see data in this.pickListOptions;.
What should the data look like in this.pickListOptions;

Reply
Phuc June 5, 2024 - 12:26 pm

Hello
When trying the new picklist is never populated. I just see ‘Choose Type’
this.data.forEach(ele => {
ele.pickListOptions = this.pickListOptions;
})
Even though there in this.pickListOptions it does not update ele.pickListOptions
Thoughts? also, can this replace a picklist field that is being populated on load. So if there is a value selected for then record will it show that value?
Thanks

Reply
Rijwan Mohmmed June 7, 2024 - 3:42 am

Hi @Phuc, Please book a meeting on below link https://topmate.io/rijwan_mohmmed

Reply
Arsenio June 18, 2024 - 11:55 am

Currently the picklist API name is showing in the non-editable format, can we show the label instead of the picklist?

Reply
Divya July 1, 2024 - 10:56 am

Hi Rijwan,

Thank you very much for sharing the code. I tried to implement this in my opportunity object related list opportunity products. I have created a button that opens the lightning data table. Somehow, even after trying several times I couldn’t change my type from text to picklist field.
Also, I have width as controlling field for length picklist field.

Please find my main component js code below,

import { LightningElement, wire, api, track } from ‘lwc’;
import { NavigationMixin } from ‘lightning/navigation’;
import { ShowToastEvent } from ‘lightning/platformShowToastEvent’;
import { refreshApex } from ‘@salesforce/apex’;
import getOpportunityProducts from ‘@salesforce/apex/OpportunityProductController.getOpportunityProducts’;
import updateOpportunityProducts from ‘@salesforce/apex/OpportunityProductController.updateOpportunityProduct’;
import deleteOpportunityProduct from ‘@salesforce/apex/OpportunityProductController.deleteOpportunityProduct’;
import OPPORTUNITYLINEITEM_OBJECT from ‘@salesforce/schema/OpportunityLineItem’;
import { getPicklistValues, getObjectInfo } from ‘lightning/uiObjectInfoApi’;
import UNIT_OF_MEASURE_FIELD from ‘@salesforce/schema/OpportunityLineItem.Unit_of_Measure__c’;
import WIDTH_FIELD from ‘@salesforce/schema/OpportunityLineItem.Width__c’;
import LENGTH_FIELD from ‘@salesforce/schema/OpportunityLineItem.Length__c’;

export default class OppProductEdit extends NavigationMixin(LightningElement) {
@api recordId;
@track opportunityProducts = [];
@track draftValues = [];
wiredOpportunityProductsResult;
unitOfMeasureOptions;
widthOptions;
lengthOptions;

columns = [
{ label: ‘Product ID’, fieldName: ‘Product2Id’, type: ‘text’ },
{ label: ‘Quantity’, fieldName: ‘Quantity’, type: ‘number’, editable: true },
{ label: ‘Unit of Measure’, fieldName: ‘Unit_of_Measure__c’, type: ‘picklist’,
typeAttributes: { placeholder: ‘Choose…’, options: { fieldName: ‘unitOfMeasureOptions’ },
value: { fieldName: ‘Unit_of_Measure__c’ }, context: { fieldName: ‘Id’ } }, editable: true },
{ label: ‘Unit Price’, fieldName: ‘UnitPrice’, type: ‘currency’, editable: true },
{ label: ‘Description’, fieldName: ‘Description’, type: ‘text’, editable: true },
{ label: ‘Width’, fieldName: ‘Width__c’, type: ‘picklist’,
typeAttributes: { placeholder: ‘Choose…’, options: { fieldName: ‘widthOptions’ },
value: { fieldName: ‘Width__c’ }, context: { fieldName: ‘Id’ } }, editable: true },
{ label: ‘Length’, fieldName: ‘Length__c’, type: ‘picklist’, typeAttributes: { placeholder: ‘Choose…’, options: { fieldName: ‘lengthOptions’ }, value: { fieldName: ‘Length__c’ }, context: { fieldName: ‘Id’ } }, editable: true },
{ label: ‘Product Code’, fieldName: ‘ProductCode’, type: ‘text’ },
{ label: ‘Total Price’, fieldName: ‘TotalPrice’, type: ‘currency’ },
{
type: ‘button-icon’,
typeAttributes: {
iconName: ‘utility:delete’,
name: ‘delete’,
title: ‘Delete’,
variant: ‘bare’,
alternativeText: ‘Delete’
}
}
];

@wire(getObjectInfo, { objectApiName: OPPORTUNITYLINEITEM_OBJECT })
objectInfo;

//Fetch picklist options
@wire(getPicklistValues, { recordTypeId: ‘$objectInfo.data.defaultRecordTypeId’, fieldApiName: UNIT_OF_MEASURE_FIELD })
unitOfMeasureValues({ error, data }) {
if (data) this.unitOfMeasureOptions = data.values;
else if (error) this.showToast(‘Error’, ‘Failed to load Unit of Measure options’, ‘error’);
}

@wire(getPicklistValues, { recordTypeId: ‘$objectInfo.data.defaultRecordTypeId’, fieldApiName: WIDTH_FIELD })
widthValues({ error, data }) {
if (data) this.widthOptions = data.values;
else if (error) this.showToast(‘Error’, ‘Failed to load Width options’, ‘error’);
}

@wire(getPicklistValues, { recordTypeId: ‘$objectInfo.data.defaultRecordTypeId’, fieldApiName: LENGTH_FIELD })
lengthValues({ error, data }) {
if (data) this.lengthOptions = data.values;
else if (error) this.showToast(‘Error’, ‘Failed to load Length options’, ‘error’);
}

@wire(getOpportunityProducts, {picklist: ‘$picklistOptions’})
OpportunityLineItemData(result) {
this.OpportunityLineItemData = result;
if(result.data){
this.data = JSON.parse(JSON.stringify(result.data));
this.data.forEach(ele => {
ele.pickListOptions = this.pickListOptions;
})
this.lastSavedData = JSON.parse(JSON.stringify(this.data));
} else if (result.error){
this.data = undefined;
}

}

updateDataValues(updateItem) {
let copyData = JSON.parse(JSON.stringify(this.data));

copyData.forEach(item => {
if (item.Id === updateItem.Id) {
for (let field in updateItem) {
item[field] = updateItem[field];
}
}
});

//write changes back to original data
this.data = […copyData];
}

updateDraftValues(updateItem) {
let draftValueChanged = false;
let copyDraftValues = […this.draftValues];
//store changed value to do operations
//on save. This will enable inline editing &
//show standard cancel & save button
copyDraftValues.forEach(item => {
if (item.Id === updateItem.Id) {
for (let field in updateItem) {
item[field] = updateItem[field];
}
draftValueChanged = true;
}
});

if (draftValueChanged) {
this.draftValues = […copyDraftValues];
} else {
this.draftValues = […copyDraftValues, updateItem];
}
}

//handler to handle cell changes & update values in draft values
handleCellChange(event) {
//this.updateDraftValues(event.detail.draftValues[0]);
let draftValues = event.detail.draftValues;
draftValues.forEach(ele=>{
this.updateDraftValues(ele);
})
}

@wire(getOpportunityProducts, { opportunityId: ‘$recordId’ })
wiredOpportunityProducts(result) {
this.wiredOpportunityProductsResult = result;
if (result.data) {
this.opportunityProducts = result.data;
} else if (result.error) {
this.showToast(‘Error’, result.error.body.message, ‘error’);
}
}

handleSave(event) {
const recordsInputs = event.detail.draftValues.slice().map(draft => {
const fields = { …draft, Id: draft.Id };
return { fields };
});

const promises = recordsInputs.map(recordInput =>
updateOpportunityProducts({ data: recordInput })
);

Promise.all(promises)
.then(() => {
this.showToast(‘Success’, ‘Products updated successfully.’, ‘success’);
this.draftValues = [];
return refreshApex(this.wiredOpportunityProductsResult);
})
.catch(error => {
this.showToast(‘Error’, error.body.message, ‘error’);
});
}

handleCancel() {
console.log(‘Navigating back to record page:’, this.recordId);
// Standard navigation
this[NavigationMixin.Navigate]({
type: ‘standard__recordPage’,
attributes: {
recordId: this.recordId,
objectApiName: ‘Opportunity’,
actionName: ‘view’
}
});

// Fallback navigation
setTimeout(() => {
window.location.href = ‘/’ + this.recordId;
}, 500); // Delay to allow standard navigation to process first
}

handleRowAction(event) {
const actionName = event.detail.action.name;
const row = event.detail.row;
if (actionName === ‘delete’) {
this.deleteProduct(row.Id);
}
}

deleteProduct(productId) {
deleteOpportunityProduct({ productId })
.then(() => {
this.showToast(‘Success’, ‘Product deleted successfully’, ‘success’);
return refreshApex(this.wiredOpportunityProductsResult);
})
.catch(error => {
this.showToast(‘Error’, error.body.message, ‘error’);
});
}

showToast(title, message, variant) {
this.dispatchEvent(
new ShowToastEvent({
title,
message,
variant
})
);
}
}

Reply
Rijwan Mohmmed July 2, 2024 - 4:20 am

Hi @Divya, Please book a meeting on below link https://topmate.io/rijwan_mohmmed

Reply

Leave a Comment

* By using this form you agree with the storage and handling of your data by this website.