1

I have built an LWC which utilizes a lightning datatable. I want to replace the standard save and cancel with my own custom lightning buttons. I am using suppress-bottom-bar which hides the standard buttons as expected.

One way I though I could achieve this is by pulling in the datatable draftValues in the oncellchange and assemble the JSON through the use of event.detail.draftValues. I then have to regenerate the JSON so I can send it to the Apex controller to persist the data.

Is there a better way to do this? The use of oncellchange does not seem efficient. Can I somehow capture the same event from the datatable that would be available on the standard onsave which would render the properly formed JSON.

Shown below is the json for two rows which I pulled from the event.detail.draftValues from the onsave.

[
  {
    "Product_Type__c": "C",
    "Rolled_In__c": "11",
    "PROJ_Year_2__c": "13",
    "PROJ_Year_3__c": "54",
    "PROJ_Year_1__c": "21",
    "Id": "0QL02000000H3UZGA0"
  },
  {
    "Product_Type__c": "U",
    "Rolled_In__c": "41",
    "PROJ_Year_2__c": "43",
    "PROJ_Year_3__c": "44",
    "PROJ_Year_1__c": "22",
    "Id": "0QL02000000H3UlGAK"
  }
]

Again is there a better way to do this or will I have to assemble the JSON from the oncellchange. If I do have to assemble the JSON which is the best approach to achieve this.

1 Answer 1

3

The draftValues attribute can be read at any time. You don't need an event to get the draft values.

handleSaveClick() {
  let draftValueJSON = JSON.stringify(
    this.template.querySelector('lightning-datatable').draftValues
  );
  // Do something with draftValueJSON //
}
4
  • Thank you. The querySelector is a powerful feature I use it all the time. Not sure why I didn't think of that.
    – bluray
    Commented Feb 24, 2021 at 20:59
  • @bluray The LWC documentation makes it feel like you can't write a value used by the parent component, so it makes sense that you might assume this (I know I did, and I'm a long-term dev). I only discovered this quite by accident on a different question.
    – sfdcfox
    Commented Feb 24, 2021 at 23:53
  • Touche' Well said @sfdcfox. I couldn't agree more. This component is loaded with features and their is a lot you can do. But this time around aligning the datatable and its features/implementation with the client's use case was quite challenging. I had to do some digging to get everything to line up with the requirements. Thanks again.
    – bluray
    Commented Feb 25, 2021 at 14:23
  • "Retrieve the new value using event.detail.draftValues." developer.salesforce.com/docs/component-library/bundle/… This is so powerful we don't need our own events.
    – peevesy
    Commented Aug 3, 2022 at 15:19

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .