1

I am trying to save a record that a user creates using a form. I get a strange error description as "Undefined" which I do not understand. Below is my component, controller and helper class. The save is happening in controller class and helper class I use to initialize an empty record(Boatreview__c) with its parent record(Boat__c) Id populated.

enter image description here

I printed the boatReview attribute that is which I believe executed by saveRecord. Here is what the object looks like:

enter image description here

Below is how the Object JSON looks like. I am confused how there are two Name fields and comment fields. One is null and other one has the value of Name which I entered through form. May be this causing some issue.

enter image description here

Component:

<aura:component implements="flexipage:availableForAllPageTypes,force:hasRecordId" description="AddBoatReview">
<aura:attribute name="boat" type="Boat__c"/>
<aura:attribute name="boatReview" type="BoatReview__c" access="private"
                default="{'sobjectType':'BoatReview__c','Id':'','Boat__c':'', 'Name':'', 'Comment__c':''}"/>
    <aura:attribute name="record" type="BoatReview__c" access="private"/>
    <aura:attribute name="recordError" type="String" access="private"/>
    <aura:handler name="init" value="{!this}" action="{!c.doInit}" />
    <force:recordData aura:id="service"
                      fields="Id, Name, Comment__c, Boat__c"
                      targetError="{!v.recordError}"
                      targetRecord="{!v.record}"
                      targetFields="{!v.boatReview}"
                      recordUpdated="{!c.onRecordUpdated}"/>

    <form class="slds-form--stacked">
        <lightning:input label="Title"
                         value="{!v.boatReview.Name}"/>
        <lightning:inputRichText title="Description"
                         value="{!v.boatReview.Comment__c}"/>
        <lightning:button label="Submit"
                          class="slds-m-top--medium"
                          iconName="utility:save"
                          variant="brand"
                          onclick="{!c.onSave}"/>
    </form>

    <aura:if isTrue="{!not(empty(v.recordError))}">
        <div class="recordError">
                {!v.recordError}</div>
    </aura:if>
</aura:component>

Controller:

({
    doInit:function (component,event,helper) {
        var eventParams = event.getParams();
        helper.onInit(component,eventParams);
    },
    onRecordUpdated:function (component,event,helper) {

    },
    onSave:function (component,event,helper) {
        console.log('Enters the Save method');
        var recordData = component.find("service");
        // Prepare a new record from template
        recordData.saveRecord($A.getCallback(function(saveResult) {
            console.log('Enter saverecord Funtion ');
            if (saveResult.state === "ERROR") {
                var errMsg = "";
                // saveResult.error is an array of errors,
                // so collect all errors into one message
                for (var i = 0; i < saveResult.error.length; i++) {
                    errMsg += saveResult.error[i].message + "\n";
                }
                component.set("v.recordError", errMsg);
                console.log('Saved Error ' + errMsg);
            } else {
                console.log('Saved Success ');
                component.set("v.recordSaveError", "");
                var toastEvent = $A.get("e.force:showToast");
                toastEvent.setParams({
                    "title": "Success!",
                    "message": "The record has been Saved successfully."
                });
                toastEvent.fire();
            }
        }));
    }


})

Helper:

({

    onInit: function(component,event){

       console.log('onInit Helper funciton in ' + event.changeType);
        console.log('component value is ' + JSON.stringify(component.get("v.boat")));
        console.log('component value is ' + JSON.stringify(component.get("v.boatReview")));
        component.find("service").getNewRecord(
            "BoatReview__c", // sObject type (objectApiName)
            null,      // recordTypeId
            false,     // skip cache?
            $A.getCallback(function() {
                var rec = component.get("v.record");
                var error = component.get("v.recordError");
                if(error || (rec === null)) {
                    console.log("Error initializing record template: " + error);
                    return;
                }
                console.log("Record template initialized: " + JSON.stringify(rec));
                rec.fields.Boat__c = component.get("v.boat").Id;
                console.log("Record template initialized: " + JSON.stringify(rec));
                component.set("v.boatReview",rec);
            })
        );
    }


})

Any suggestions where I should look to debug this. Not sure what is going on in SaveRecord of LDS.

0

Helper class

/* taken out boat id assignment */

({

onInit: function(component,event){

   console.log('onInit Helper funciton in ' + event.changeType);
    console.log('component value is ' + JSON.stringify(component.get("v.boat")));
    console.log('component value is ' + JSON.stringify(component.get("v.boatReview")));
    component.find("service").getNewRecord(
        "BoatReview__c", // sObject type (objectApiName)
        null,      // recordTypeId
        false,     // skip cache?
        $A.getCallback(function() {
            var rec = component.get("v.record");
            var error = component.get("v.recordError");
            if(error || (rec === null)) {
                console.log("Error initializing record template: " + error);
                return;
            }
            console.log("Record template initialized: " + JSON.stringify(rec));
            console.log("Record template initialized: " + JSON.stringify(rec));
            component.set("v.boatReview",rec);
        })
    );
}

})

Controller Class:

/* Added the Boat__c Id assignment here */

({
doInit:function (component,event,helper) {
    var eventParams = event.getParams();
    helper.onInit(component,eventParams);
},
onRecordUpdated:function (component,event,helper) {

},
onSave:function (component,event,helper) {
    console.log('Enters the Save method');
    var recordData = component.find("service");
   component.set("v.record.Boat__c", component.get("v.recordId"));
    // Prepare a new record from template
    recordData.saveRecord($A.getCallback(function(saveResult) {
        console.log('Enter saverecord Funtion ');
        if (saveResult.state === "ERROR") {
            var errMsg = "";
            // saveResult.error is an array of errors,
            // so collect all errors into one message
            for (var i = 0; i < saveResult.error.length; i++) {
                errMsg += saveResult.error[i].message + "\n";
            }
            component.set("v.recordError", errMsg);
            console.log('Saved Error ' + errMsg);
        } else {
            console.log('Saved Success ');
            component.set("v.recordSaveError", "");
            var toastEvent = $A.get("e.force:showToast");
            toastEvent.setParams({
                "title": "Success!",
                "message": "The record has been Saved successfully."
            });
            toastEvent.fire();
        }
    }));
}

})

When the component is loaded your Init functionality is called and the record is initialized.

And on click of save onSave functionality is called.

  • That did not help. I tried assigning the parent object Id in the controller. It gave me the same undefined error. I tried using it with boatReview attribute also like - component.set("v.boatReview.Boat__c", component.get("v.boat.Id"));. But that did not help. – Arnold Dec 27 '17 at 14:23
  • component.set("v.boatReview.Boat__c", component.get("v.boat").Id);. It seems we cannot get a value like - component.get("v.record.Boat__c") - this gives undefined. – Arnold Dec 27 '17 at 14:34
  • I have added the object JSON. Does that give you any idea? – Arnold Dec 27 '17 at 14:52
0

The error looks like it is coming from your use of targetRecord and targetFields

Target Record returns data other than just the field values including display values when you reference the field. Salesforce added Target Fields as a way to access the field values a little more directly.

Target Record : {"fields":{"Id":{"displayValue":null,"value":"a1I0x0000006GF7EAM"}}} Target Fields : {"Id":"a1I0x0000006GF7EAM"}

So your line rec.fields.Boat__c = component.get("v.boat").Id;

needs to be written out as

rec.fields.Boat__c.value = component.get("v.boat").Id;

If later you wanted to get a value from a field in targetRecord you'd need to reference it like

component.get("v.record.fields.Boat__c.value")

If you were to add this to targetFields I'd reference it like

v.boatReview.Id = component.get("v.boat").Id

or to get the value

component.get("v.boatReview.Id")

I generally prefer targetFields because it is so much more direct, but it is a matter of preference because of the additional returns of targetRecord.

At the end of your helper you are setting targetFields with the targetRecord, and these objects have different formats so that is also likely causing some problems. It shouldn't be necessary to use both targetFields and targetRecord. There is also a pretty good trailhead module that goes into a lot of this in detail, definitely worth the time it takes to read it (it is pretty long).

If you're still getting errors, try looking at the entire save result to see if there is other data you're filtering out. I doubt you are but it is worth a look

console.log('Save Result : ' + JSON.stringify(saveResult));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.