9

In Lightning component we have relational fields (e.g. CustObjA.CustObj__r.Name) which we use in lighthing component. This is on component as,

<ui:inputText class="slds-input" value="{!v.Item.CustObj__r.Name}" />

For existing objects we use SOQL to retrieve,

List<CustObjA> listObjs = [SELECT Startdate, CustObj__r.Name
FROM CustObjA];

This is working fine. But If we don't have records for the object, we would want to initialize sObject CustObjA with relational fields

I'm trying below approach.

List<CustObjA> listObjs = new List<CustObjA>();

CustObjA newObj = new CustObjA();
newObj.CustObj__c = new CustObj__c(name = 'test');

listObjs .add(newObj);

But this approach seems not resulting an object which I can refer CustObj__r.Name. Instead I'm getting below run-time exception.

Attempt to de-reference a null object

What is the correct way of initializing an object with Relational fields? Appreciate any help. Thanks.

1 Answer 1

12

You need to use the name pointing reference:

MyObject__c record = new MyObject__c();
record.Parent__r = new Parent__c(Name='Populated');

The above is functionally equivalent to putSObject:

MyObject__c record = new MyObject__c();
record.putSObject('Parent__r', new Parent__c(Name='Populated'));

You can also use name=value pairs in the constructor for CPU savings:

 MyObject__c record = new MyObject__c(Parent__r=new Parent__c(Name='...'));
2
  • Any benchmark or documentation about this "CPU saving" ?
    – Simonp
    May 21, 2017 at 10:59
  • @SimonPlacentino I did some profiling here. I realize you commented a long time ago, but I didn't see it.
    – Adrian Larson
    Sep 20, 2019 at 15:41

You must log in to answer this question.

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