Disclaimer: My answer to this question does not deal with a real business use case scenario. The approach mentioned in my answer was found to be working while going through this question. The answer can be definitely improved/fine-tuned based on real business use case scenarios.
Going through the LWC documentation or the lwc-recipe, there does not seem to be a scenario which discusses how to pass a SObject
record from LWC to a custom Apex method to persist data. All the examples in documentation or lwc-recipe only discusses about fetching data.
The ones available are using the lightning/ui*APi*
createRecord()
or updateRecord()
, but what if I need to pass it to custom Apex methods evaluating more complex logic before DML operations?
So, how do we send a SObject
record to a custom Apex method for performing DML operations?
Let's say we have the following Use Case Scenarios:
- Create a new
SObject
record by constructing an instance of theSObject
and passing values from LWC to a custom Apex method performing insert - Update a
SObject
record fetched on LWC using@wire
service by passing values from LWC to a custom Apex method performing updates
Best Answer
Here is my code which I use to CRU records in LWC. Fairly basic example. I am not using String or JSON manipulation. I am also using static binding using fieldName imports
HTML:
`
JS:
Apex: