[SalesForce] Lightning Data Service – Dynamic Fields

I am creating a dynamic navigation (button) component to be used throughout the org. I am trying to provide system admins the ability to specify the data (field/fields) to be retrieved by the force:recordData component (lightning data service) so the values will be available and can be referenced when constructing the external url.

To achieve this, I am exposing a String attribute as a design element called 'fieldAPIName'. The admin would then specify the field's API Name i.e. AccountId. I am then using that attribute as follows;

<force:recordData recordId="{!v.recordId}" 
                fields="{!'Id,'+v.fieldAPIName}"  
                targetFields="{!v.record}" 
                aura:id="recordData"
                recordUpdated="{!c.recordLoaded}"
                mode="VIEW"/> 

The recordData 'fields' attribute is a String array. You cannot have a String Array as a design element, so I am using a String element to retrieve the field names and appending it to the Id (as above) to effectively simulate the following;

    <force:recordData recordId="{!v.recordId}" 
                fields="Id, AccountId"  
                targetFields="{!v.record}" 
                aura:id="recordData"
                recordUpdated="{!c.recordLoaded}"
                mode="VIEW"/> 

When the page loads I am receiving the following error:

Action failed: force:record$controller$init [type error on parameter fields: expected String[], found string]

I'd like to avoid a server side call if possible and avoid the FULL layoutType approach (so the field does not have to be on the layout to be available).

I'm probably missing something obvious. Any help would be greatly appreciated!

Best Answer

You can do client-side parsing of the value:

<aura:attribute name="fieldNames" type="String" default="Id" />
<aura:attribute name="fieldNameList" access="private" type="String[]" default="['Id']" />
<aura:handler name="init" value="{!this}" action="{!c.doInit}" />

<force:recordData recordId="{!v.recordId}" 
            fields="{!v.fieldNameList}"  
            targetFields="{!v.record}" 
            aura:id="recordData"
            recordUpdated="{!c.recordLoaded}"
            mode="VIEW"/> 

doInit: function(component, event, helper) {
  component.set("v.fieldNameList", component.get("v.fieldNames").split(","));
  // ...
},

Alter this code as appropriate to check for errors, etc.

Related Topic