[SalesForce] confused on force:recordData!

while I'm going through the tutorial on Lightning Data Service, I can see that they use force:record data to perform all the CRUD operation and eliminate the need to write apex controller. but I did not understand the following syntax they use for it.

Please look at this link

code:

 <aura:attribute name="newContact" type="Object"/>
<aura:attribute name="simpleNewContact" type="Object"/>
<aura:attribute name="newContactError" type="String"/>

<aura:handler name="init" value="{!this}" action="{!c.doInit}"/>

<force:recordData aura:id="contactRecordCreator" 
                  layoutType="FULL"
                  targetRecord="{!v.newContact}"
                  targetFields="{!v.simpleNewContact}"
                  targetError="{!v.newContactError}" />

My question is: why are we defining two attributes namely newContact and simpleNewContact of type "Object" and assigning newContact in targetRecord and and simpleNewContact in targetField and why not use a single attribute named simpleNewContact alone.what is the purpose of newContact. also I'm searching for the definition targetRecord,targetFields,targetError please provide any link that explains in detail.

Best Answer

There is some description of targetFields in the Lightning Data Service (Beta) release notes:

force:recordData includes a new attribute called targetFields, which is populated with a simplified view of the record’s fields. targetFields is automatically updated whenever Lightning Data Service detects a record change. v.targetFields.Name is equivalent to v.targetRecord.fields.Name.value. A simple way to update force:recordPreview usage to force:recordData is to change references from targetRecord to targetFields.

So its worth setting up this attribute so you have a more convenient way to reference the fields in your component e.g.:

v.targetFields.Name 

instead of:

v.targetRecord.fields.Name.value

so getting rid of .fields and .value that would otherwise have to be present in every reference in the markup. Essentially force:recordData is keeping two JavaScript data structures in sync for you, where the targetFields one is generally easier and cleaner to use in the component markup.

(And it also makes replacing force:recordPreview with force:recordData simple.)

PS

Mohith's comment on your question contains a key point that I didn't know that makes things clearer: "Recommend using targetFields and you can drop the targetRecord". So the point is that targetRecord is only there for backward compatibility and new code is best written using targetFields only. Suggest you prompt him to post that as an answer and accept that answer instead.

Related Topic