[SalesForce] How to initialize sObject with Relational fields

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.

Best Answer

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='...'));
Related Topic