function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
JaanuJaanu 

Unable to save the record in lightning data services.

I am unable to save the record in LDS. can you pls help me.. Here is the component and controller. 
Component
         <lightning:recordEditForm recordId="{!v.recordId}" objectApiName="Prescription__c" >

             <lightning:recordViewForm recordId="{!v.pacctId}" objectApiName="Account"> --> This is coming from Acct Object
                   <lightning:outputField fieldName="FirstName" />
                   <lightning:outputField fieldName="LastName" />
            </lightning:recordViewForm> 

           <lightning:recordViewForm recordId="{!v.pacctId}" objectApiName="Pre__c">  --> This is coming from different Object
                   <lightning:outputField fieldName="P_First_Name__c" />
                   <lightning:outputField fieldName="P_Last_Name__c" />        
            </lightning:recordViewForm>               
             
             <div class="slds-p-horizontal--small">
            <lightning:inputField fieldName="Name" />  --> These fields are input fields from 3rd Object which needs to be saved ultimately.
                <lightning:input fieldName="D__c" />   
                <lightning:inputField fieldName="R__c" />
                <lightning:inputField fieldName="O__c" />                     
             </div>
                <br/>

                <lightning:layoutItem padding="around-small">
                    <lightning:button class="slds-button slds-button--brand" label="Next" onclick="{!c.handleSuccess}" variant="brand" />
                </lightning:layoutItem>

controller
     handleSuccess : function(component, event, helper) {
        alert('I am in the Prescription success function # ' + component.get("v.pacctId"));
        component.set("v.simpleInsertP.Pa__c", component.get("v.pacctId"));
        component.set('v.simpleInsertPr.H_A__c', component.get("v.hcpId")); 
        alert(' I am here at 33333333 ....');  - > This alert is coming... after that nothing is happening... it's not even going to IF clause.
        component.find("recordHandler").saveRecord(function(saveResult) {
        if (saveResult.state === "SUCCESS" || saveResult.state === "DRAFT") {
            alert(' I am here at 2222222 ....');
            var toastEvent = $A.get("e.force:showToast");
            toastEvent.setParams({
                "title": "Success!",
                "message": "Prescription Record created Successfully!",
                "type": "success"
            });
Best Answer chosen by Jaanu
Khan AnasKhan Anas (Salesforce Developers) 
Hi Jaanu,

I trust you are doing very well.

In order to use LDS you should use force:recordData component. To save a record using Lightning Data Service, call saveRecord on the force:recordData component, and pass in a callback function to be invoked after the save operation completes.

You can refer to below link for more information.

https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/data_service.htm

https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/data_service_save_record.htm


Below is the sample code to save a record using LDS. Kindly modify it according to your requirement.

sObject : Customer__c
Fields : Name, Email__c, Address__c, Telephone__c

Component:
<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" >
    <aura:attribute name="customer" type="Object" description="The record object to be displayed"/>
    <aura:attribute name="customerRecord" type="Object" description="A simplified view record object to be displayed"/>
    <aura:attribute name="recordSaveError" type="String" description="An error message bound to force:recordData"/>
    
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
    
    <force:recordData aura:id="cusRec" 
                      layoutType="FULL" 
                      recordId="{!v.recordId}"  
                      targetError="{!v.recordSaveError}"
                      targetRecord="{!v.customer}"
                      targetFields="{!v.customerRecord}"
                      mode="EDIT" />
    
    <div class="slds-text-heading_medium">
        New Customer
    </div>
    <br/>
    <div class = "slds-size--3-of-8">
        <lightning:input label="Name" value="{!v.customerRecord.Name}"/>
        <br/>
        <lightning:input type="email" label="Email" value="{!v.customerRecord.Email__c}"/>
        <br/>
        <lightning:input type="tel" label="Telephone" value="{!v.customerRecord.Telephone__c}"/>
        <br/>
        <lightning:textarea label="Address" value="{!v.customerRecord.Address__c}"/>
        <br/>
        <lightning:button label="Submit" onclick="{!c.saveCustomer}"/>
    </div>        
    
    <aura:if isTrue="{!not(empty(v.recordSaveError))}">
        <br />
        <div class="error slds-box">
            {!v.recordSaveError}
        </div> 
    </aura:if>
</aura:component>

Controller:
({
    doInit: function(component, event, helper) {
        // Prepare a new record from template
        component.find("cusRec").getNewRecord(
            "Customer__c", //Object Type (ObjectAPI)
            null,      // recordTypeId
            false,     // skip cache?
            $A.getCallback(function() {
                var rec = component.get("v.customer");
                var error = component.get("v.recordSaveError");
                if(error || (rec === null)) {
                    console.log("Error initializing record template: " + error);
                    return;
                }
                console.log("Record template initialized: " + rec.sobjectType);
            })
        );
    },
    
    saveCustomer : function(component, event, helper) {
        component.find("cusRec").saveRecord($A.getCallback(function(saveResult) {
            if (saveResult.state === "SUCCESS" || saveResult.state === "DRAFT") {
                console.log("Save completed successfully.");
                component.set('v.customerRecord','');
            } 
            else if (saveResult.state === "INCOMPLETE") {
                component.set("v.recordSaveError","User is offline, device doesn't support drafts.");
            } 
            else 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.recordSaveError", errMsg);    
            }
            else {
            	component.set("v.recordSaveError",'Unknown problem, state: ' + saveResult.state + ', error: ' + 
                               JSON.stringify(saveResult.error));
            }
        }));
    },
})

I hope it helps you.

Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in future.

Thanks and Regards,
Khan Anas

All Answers

Khan AnasKhan Anas (Salesforce Developers) 
Hi Jaanu,

I trust you are doing very well.

In order to use LDS you should use force:recordData component. To save a record using Lightning Data Service, call saveRecord on the force:recordData component, and pass in a callback function to be invoked after the save operation completes.

You can refer to below link for more information.

https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/data_service.htm

https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/data_service_save_record.htm


Below is the sample code to save a record using LDS. Kindly modify it according to your requirement.

sObject : Customer__c
Fields : Name, Email__c, Address__c, Telephone__c

Component:
<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" >
    <aura:attribute name="customer" type="Object" description="The record object to be displayed"/>
    <aura:attribute name="customerRecord" type="Object" description="A simplified view record object to be displayed"/>
    <aura:attribute name="recordSaveError" type="String" description="An error message bound to force:recordData"/>
    
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
    
    <force:recordData aura:id="cusRec" 
                      layoutType="FULL" 
                      recordId="{!v.recordId}"  
                      targetError="{!v.recordSaveError}"
                      targetRecord="{!v.customer}"
                      targetFields="{!v.customerRecord}"
                      mode="EDIT" />
    
    <div class="slds-text-heading_medium">
        New Customer
    </div>
    <br/>
    <div class = "slds-size--3-of-8">
        <lightning:input label="Name" value="{!v.customerRecord.Name}"/>
        <br/>
        <lightning:input type="email" label="Email" value="{!v.customerRecord.Email__c}"/>
        <br/>
        <lightning:input type="tel" label="Telephone" value="{!v.customerRecord.Telephone__c}"/>
        <br/>
        <lightning:textarea label="Address" value="{!v.customerRecord.Address__c}"/>
        <br/>
        <lightning:button label="Submit" onclick="{!c.saveCustomer}"/>
    </div>        
    
    <aura:if isTrue="{!not(empty(v.recordSaveError))}">
        <br />
        <div class="error slds-box">
            {!v.recordSaveError}
        </div> 
    </aura:if>
</aura:component>

Controller:
({
    doInit: function(component, event, helper) {
        // Prepare a new record from template
        component.find("cusRec").getNewRecord(
            "Customer__c", //Object Type (ObjectAPI)
            null,      // recordTypeId
            false,     // skip cache?
            $A.getCallback(function() {
                var rec = component.get("v.customer");
                var error = component.get("v.recordSaveError");
                if(error || (rec === null)) {
                    console.log("Error initializing record template: " + error);
                    return;
                }
                console.log("Record template initialized: " + rec.sobjectType);
            })
        );
    },
    
    saveCustomer : function(component, event, helper) {
        component.find("cusRec").saveRecord($A.getCallback(function(saveResult) {
            if (saveResult.state === "SUCCESS" || saveResult.state === "DRAFT") {
                console.log("Save completed successfully.");
                component.set('v.customerRecord','');
            } 
            else if (saveResult.state === "INCOMPLETE") {
                component.set("v.recordSaveError","User is offline, device doesn't support drafts.");
            } 
            else 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.recordSaveError", errMsg);    
            }
            else {
            	component.set("v.recordSaveError",'Unknown problem, state: ' + saveResult.state + ', error: ' + 
                               JSON.stringify(saveResult.error));
            }
        }));
    },
})

I hope it helps you.

Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in future.

Thanks and Regards,
Khan Anas
This was selected as the best answer
JaanuJaanu
not working ....
All my other components LDS is working fine ... for some reason ... this component is not going to the below if clause at all ... it's completely exiting the IF clause ...I have alert after the IF clause(after all ELSE clauses)...that's only coming ...

In this componet I am displaying fields from 2 objects (just output fields)... and input from one object.

if (saveResult.state === "SUCCESS" || saveResult.state === "DRAFT") {
JaanuJaanu
I am getting record null error message when trying to save... any help pls
Khan AnasKhan Anas (Salesforce Developers) 
Hi Jaanu,

Did you copy-paste my code correctly?

Please share your complete code with the error message.

Regards,
Khan Anas

 
JaanuJaanu
I have coded lot of components in LDS which all working fine except this. Not sure why ... it's not going to save record function ... when I display the recordId after the saverecord function ... it displays NULL.. 

I did not work with your code ...I have psted my code above..do you see any issues with that please ?
Khan AnasKhan Anas (Salesforce Developers) 
Hi Jaanu,

In your code, I can't find <force:recordData> with aura:id="recordHandler" 

I suggest you go through my code and you will definitely get the result.


Regards,
Khan Anas 
JaanuJaanu
I have both of them declared ...