There are several topics related to this issue:
- Salesforce LWC - Pass standard object to Apex Class
- How do I pass sObject record from LWC to Apex Controller?
- How do I pass a SObject record from LWC to a custom Apex method to persist data?
I tried the different solutions suggested and all of them have worked correctly.
- Specify the sobjectype parameter as stated in this answer.
const record = {
sobjectType: "Account",
Name: "Demo",
Phone: "11111111"
};
Build an object where the name of their properties matches the API Name of the field being referenced.
- The property name is set as a string as stated in this Gist.
- Using @salesforce/schema as stated in this answer.
First example:
const record = {
Name: 'Demo',
Phone: '11111111'
};
Second example:
import ACCOUNT_NAME from "@salesforce/schema/Account.Name";
import ACCOUNT_PHONE from "@salesforce/schema/Account.Phone";
const record = {
[ACCOUNT_NAME.fieldApiName]: 'Demo',
[ACCOUNT_PHONE.fieldApiName]: '11111111',
}
However, if you try to access sObject fields through relationships it doesn't work. Accessing the sObject field passed to the Apex controller the value is null.
You can specify up to 5 levels of spanning fields. For example, Opportunity.Account.CreatedBy.LastModifiedById returns 4 levels of spanning fields.
import ACCOUNT_NAME from "@salesforce/schema/Account.Name";
import CONTACT_EMAIL from "@salesforce/schema/Account.Contact.Email";
const record = {
[ACCOUNT_NAME.fieldApiName]: 'Demo',
[CONTACT.EMAIL.fieldApiName]: '[email protected]',
}
Why are the related fields not received by the Apex controller?
Generally, an sObject is passed as a parameter to perform some DML action from the controller. In such cases the related fields don't make sense.
In some cases DML actions are not needed, but the sObject and its related fields are necessary, and try to avoid:
- Run a query in the controller since the record has already been retrieved in the LWC.
- Wrapper Class in the Apex controller.
- Method with too many parameters.
{ Name: "Demo", Contact: { FirstName: "Fred", Id: "003..." }}
.{ Name: "Demo", Contact: { FirstName: "Fred" } }
because the contact related object doesn't include the Id field. For further information on how to pass data to Apex along retrieved data from the wire adaptergetRecord
, read "Unable to read Sobject" when passing LWC getRecord data to Apex.