[SalesForce] Can force:recordData query related parent fields

Anyone found a way to select parent fields with force:recordData?
It would be great to have something like this:

<force:recordData recordId="{!v.recordId}" targetRecord="{!v.child}"
                  layoutType="FULL" fields="parent__r.Name" recordUpdated="{!c.init}" />

init: function(cmp, evt, helper) {
    var child= cmp.get("v.child");

    if(child) {
        console.log(child.fields.parent__r.Name);
    }
}

results is undefined

Best Answer

So with some help I figured out that it works, it is just a bit dirty to get the values, this is the path through the object structure:

child.fields.parent__r.value.fields.Name.value

So the targetFields attribute on recordData just came to my mind, and I replaced targetRecord. Now it works as expected:

<force:recordData recordId="{!v.recordId}" targetFields="{!v.child}"
                  fields="parent__r.foo__c" recordUpdated="{!c.init}" />

var child = cmp.get("v.child");
console.log(child.parent__c); 
console.log(child.parent__r.Id); 
console.log(child.parent__r.Name); 
console.log(child.parent__r.foo__c); 

Notes:

  • parent__r.Name and parent__r.Id will ALWAYS be part of the data set
  • Don't forget the namespace: MY_NAMESPACE__parent__r.MY_NAMESPACE__foo__c

The max depth is 5

parent__r.parent2__r.parent3__r.parent4__r.parent5__r.bar__c

Exceeding the limit will silently fail and leave your targetFields="{!v.child}" null

  • Same as when you mistype field names in the fields="" attribute (or forgot the NS) it will tell you the miss-leading error message:

    [Cannot read property 'parent__r' of null]

Edit

Found it officially documented, hidden in the Lightning Components Developer Guide:

Lightning Data Service supports spanned fields with a maximum depth of five levels. Support for working with collections of records or for querying for a record by anything other than the record ID isn’t available. If you must support higher-level operations or multiple operations in one transaction, use standard @AuraEnabled Apex methods.

Related Topic