Pass sObject to an Apex Method From LWC Component๐ฒ

ย
One of the most interesting and useful thing i came across while working with LWC, is the ability to pass an ๐ด๐๐ฃ๐ซ๐ฆ๐ค๐ต from LWC component to Apex๐ง. This actually saves us from writing wrapper classes and assigning the fields from the same in apex in case we need to update the same object.๐ช
If you have not used it yet, here is an example๐ฌ:
๐Lets say, you need to update some fields on an Account from a LWC component based on user action.
Of course ๐ถ๐ฑ๐ฅ๐ข๐ต๐ฆ๐๐ฆ๐ค๐ฐ๐ณ๐ฅ
from '๐ญ๐ช๐จ๐ฉ๐ต๐ฏ๐ช๐ฏ๐จ/๐ถ๐ช๐๐ฆ๐ค๐ฐ๐ณ๐ฅ๐๐ฑ๐ช'
should be the first option we should be consideringโ
. But what if user normally should not have FLS to the field ๐ค๐ญ. Or the org is poorly setup and you dont have the time or authority to fix things.
This is where we can utilize the approach which i was mentioning above.๐
๐You can create a js object with field to edit from LWC and pass it to an Apex method without using any wrapper.๐
๐ญ๐ฆ๐ต ๐ณ๐ฆ๐ค๐ฐ๐ณ๐ฅ = {
๐ด๐ฐ๐ฃ๐ซ๐ฆ๐ค๐ต๐๐บ๐ฑ๐ฆ: "๐๐ค๐ค๐ฐ๐ถ๐ฏ๐ต",
๐๐ฅ: ๐ต๐ฉ๐ช๐ด.๐ณ๐ฆ๐ค๐ฐ๐ณ๐ฅ๐๐ฅ,
๐๐ช๐ฆ๐ญ๐ฅ๐๐ฐ๐๐ฑ๐ฅ๐ข๐ต๐ฆ__๐ค: "๐๐ฆ๐ธ ๐๐ข๐ญ๐ถ๐ฆ"
};
๐And then you can pass the object to an apex method from LWC component ๐
๐ถ๐ฑ๐ฅ๐ข๐ต๐ฆ๐๐ค๐ค๐ฐ๐ถ๐ฏ๐ต๐๐ช๐ฆ๐ญ๐ฅ๐ด({๐ข๐ค๐ค๐ฐ๐ถ๐ฏ๐ต๐๐ฐ๐๐ฑ๐ฅ๐ข๐ต๐ฆ:๐ณ๐ฆ๐ค๐ฐ๐ณ๐ฅ})
.๐ต๐ฉ๐ฆ๐ฏ((๐ณ๐ฆ๐ด) => ๐ค๐ฐ๐ฏ๐ด๐ฐ๐ญ๐ฆ.๐ญ๐ฐ๐จ("๐ณ๐ฆ๐ค๐ฐ๐ณ๐ฅ ๐ถ๐ฑ๐ฅ๐ข๐ต๐ฆ๐ฅ"))
.๐ค๐ข๐ต๐ค๐ฉ((๐ฆ๐ณ๐ณ๐ฐ๐ณ) => ๐ค๐ฐ๐ฏ๐ด๐ฐ๐ญ๐ฆ.๐ฆ๐ณ๐ณ๐ฐ๐ณ("๐ฆ๐ณ๐ณ๐ฐ๐ณ: " + ๐๐๐๐.๐ด๐ต๐ณ๐ช๐ฏ๐จ๐ช๐ง๐บ(๐ฆ๐ณ๐ณ๐ฐ๐ณ)));
๐Now the Apex method can written as below๐:
๐ฑ๐ถ๐ฃ๐ญ๐ช๐ค ๐ธ๐ช๐ต๐ฉ ๐ด๐ฉ๐ข๐ณ๐ช๐ฏ๐จ ๐ค๐ญ๐ข๐ด๐ด ๐๐ฆ๐ค๐ช๐ฆ๐ท๐ฆ๐ด๐๐ฃ๐ซ๐ฆ๐ค๐ต๐๐ณ๐ฐ๐ฎ๐๐๐ {
@๐๐ถ๐ณ๐ข๐๐ฏ๐ข๐ฃ๐ญ๐ฆ๐ฅ(๐ค๐ข๐ค๐ฉ๐ฆ๐ข๐ฃ๐ญ๐ฆ=๐ง๐ข๐ญ๐ด๐ฆ)
๐ฑ๐ถ๐ฃ๐ญ๐ช๐ค ๐ด๐ต๐ข๐ต๐ช๐ค ๐๐ฐ๐ฐ๐ญ๐ฆ๐ข๐ฏ ๐ถ๐ฑ๐ฅ๐ข๐ต๐ฆ๐๐ค๐ค๐ฐ๐ถ๐ฏ๐ต๐๐ช๐ฆ๐ญ๐ฅ๐ด(๐๐ค๐ค๐ฐ๐ถ๐ฏ๐ต ๐ข๐ค๐ค๐ฐ๐ถ๐ฏ๐ต๐๐ฐ๐๐ฑ๐ฅ๐ข๐ต๐ฆ){
๐๐ค๐ค๐ฐ๐ถ๐ฏ๐ต ๐ข๐ค๐ค=๐ฏ๐ฆ๐ธ ๐๐ค๐ค๐ฐ๐ถ๐ฏ๐ต(๐๐ฅ=๐ข๐ค๐ค๐ฐ๐ถ๐ฏ๐ต๐๐ฐ๐๐ฑ๐ฅ๐ข๐ต๐ฆ.๐๐ฅ);
๐ช๐ง(๐๐ต๐ณ๐ช๐ฏ๐จ.๐๐ด๐๐ฐ๐ต๐๐ญ๐ข๐ฏ๐ฌ(๐ข๐ค๐ค๐ฐ๐ถ๐ฏ๐ต๐๐ฐ๐๐ฑ๐ฅ๐ข๐ต๐ฆ?.๐๐ช๐ฆ๐ญ๐ฅ๐๐ฐ๐๐ฑ๐ฅ๐ข๐ต๐ฆ__๐ค))
{
๐ข๐ค๐ค.๐๐ช๐ฆ๐ญ๐ฅ๐๐ฐ๐๐ฑ๐ฅ๐ข๐ต๐ฆ__๐ค=๐ข๐ค๐ค๐ฐ๐ถ๐ฏ๐ต๐๐ฐ๐๐ฑ๐ฅ๐ข๐ต๐ฆ.๐๐ช๐ฆ๐ญ๐ฅ๐๐ฐ๐๐ฑ๐ฅ๐ข๐ต๐ฆ__๐ค;
}
๐ถ๐ฑ๐ฅ๐ข๐ต๐ฆ ๐ข๐ค๐ค;
๐ณ๐ฆ๐ต๐ถ๐ณ๐ฏ ๐ต๐ณ๐ถ๐ฆ;
}
}
Note that i have created new Account variable acc, reassigned the field we are expecting to this new variable from accountToUpdate variable and updated acc instead of directly updating accountToUpdate๐ซ. This is because the object accountToUpdate is created from front end JS and can be manipulated to update unintended fields by adding extra fields from front end. So as a better security practice๐ฎ, i believe its better to add this check from Apex side๐ต๏ธโโ๏ธ. You can pass a list of records in similar way!๐ฎ
You can find the code for LWC components used in my github repo
- LWC Component Name : passSobjectToApex
- Apex Class Name: RecievesObjectFromLWC.cls
This Content was originally posted in linkedin View Post