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
aks0011aks0011 

How to pass and insert Records from lightning component to apex class controller ?

Hi,

I'm trying to save an account record using lightning component but it's not working. I've the below mentioned code so please look at this and let me know if I'm missing or doing ways wrong.

thanks in advance :)


Demo.cmp
<aura:component controller="DemoPageController" implements="force:appHostable">
    <aura:attribute name="accounts" type="account"/>
    <aura:handler name="init" value="{!this}" action="{!c.doInit}" />
    <div class="slds">
        <fieldset class="slds-form--compound">
            <div class="form-element__group">
                <div class="slds-form-element__row">
                    <div class="slds-form-element slds-size--1-of-2">
                        <label class="slds-form-element__label" for="input-01">Name</label>
                        <ui:inputText class="slds-input" value="{!v.accounts.Name}"/>
                    </div>
                </div>
            </div>
        </fieldset>
        <div class="slds-form-element__row slds-p-top--small">
            <input type="button" value="Save" class="slds-button slds-button--brand"
                   onclick="{!c.submit}"/>
        </div>
    </div>
</aura:component>

DemoController.js

({
    doInit : function(component, event, helper) {
        helper.getAccounts(component);
    },
    
    submit : function(component, event, helper) {
        var newAccRec = component.get('v.accounts');
        console.log(newAccRec);
        helper.save(component, newAccRec);
    },
})

DemoHelper.js

({
    getAccounts: function(component) {
        var action = component.get("c.getAccounts");
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (component.isValid() && state === "SUCCESS") {
                component.set("v.accounts", response.getReturnValue());
            }
        });
        $A.enqueueAction(action);
    },
    
    save : function(component, newAccRec) {
        var action = component.get("c.saveRecord");
        action.setParams({
            "accountRecord": newAccRec
        });
        action.setCallback(this, function(response) {
            var isSaved = response.getReturnValue();
            if (isSaved) {
                console.log('record saved '+isSaved+' and execution ends...');
            }
            else
                console.log('record saved false and execution ends...');
        });
        $A.enqueueAction(action);
    },
})

DemoPageController.apxc

public class DemoPageController {
    @AuraEnabled
    public static Account getAccounts() {
        return new account(name = 'test light account');
    }
    
    @AuraEnabled
    public static boolean saveRecord(Account accountRecord) {
        system.debug('@apex save...' + accountRecord);
        return true;
    }
}

This above mentioned code is supposed to be worked to save a new account record in sf database.

I'm using this in SF classic as given below -:

DemoPage.vfp

<apex:page sidebar="false">
    <apex:stylesheet value="{!URLFOR($Resource.SLDS0121, 'assets/styles/salesforce-lightning-design-system-vf.css')}" />
    <apex:includeLightning />
    <div id="containerLight">
        <div id="Lightning"/>
    </div>
    
    <script>
        $Lightning.use("c:DemoApp", function(){
            $Lightning.createComponent("c:Demo",{},"Lightning",function(cmp){
                
            });
        });
    </script>
</apex:page>
Naval Sharma4Naval Sharma4
Hi,

In order to save Account in controller you have to use insert/upsert. Update your code like this.
@AuraEnabled
    public static boolean saveRecord(Account accountRecord) {
        try{
            system.debug('@apex save...' + accountRecord);
            upsert accountRecord;
            return true;
         }
         catch(Exception e){
              return false;
          }
    }

 
aks0011aks0011
Hi Naval Sharma 4,

Thanks for the consideration. Yes Naval I know to insert I need to write a DML but for now that's not an issue.
Please try and Run this code if you can and then please let me know that why it's disable to receive the record at apex class method sent from the lightning component?
aks0011aks0011
Demo.cmp
<aura:component controller="DemoPageController" implements="force:appHostable">
    <aura:attribute name="accounts" type="List"/>
    <aura:attribute name="account" type="Account"/>
    <aura:handler name="init" value="{!this}" action="{!c.doInit}" />
    <div class="slds">
        <fieldset class="slds-form--compound">
            <div class="form-element__group">
                <div class="slds-form-element__row">
                    <div class="slds-form-element slds-size--1-of-2">
                        <label class="slds-form-element__label" for="input-01">Name</label>
                        <ui:inputText class="slds-input" value="{!v.account.Name}"/>
                    </div>
                </div>
            </div>
        </fieldset>
        <div class="slds-form-element__row slds-p-top--small">
            <input type="button" value="Save" class="slds-button slds-button--brand" 
                   onclick="{!c.submit}"/>
        </div>
    </div>
</aura:component>
DemoController.js

({
    doInit : function(component, event, helper) {
        helper.getAccounts(component);
    },
    
    submit : function(component, event, helper) {
        var newAccRec = component.get('v.account');
        console.log(newAccRec);
        helper.save(component, newAccRec);
    },
})
DemoHelper.js

({
    getAccounts: function(component) {
        var action = component.get("c.getAccounts");
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (component.isValid() && state === "SUCCESS") {
                component.set("v.account", response.getReturnValue());
            }
        });
        $A.enqueueAction(action);
    },
    
    save : function(component, newAccRec) {
        var accR = [];
        accR.push(newAccRec);
        component.set('v.accounts', accR);
        var action = component.get("c.saveRecord");
        action.setParams({ 
            "accountRecord": component.get('v.accounts')
        });
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (component.isValid() && state === "SUCCESS") {
                var rec = response.getReturnValue();
                console.log(rec);
            }
        });
        $A.enqueueAction(action);
    },
})
DemoPageController.apxc

public class DemoPageController {
	@AuraEnabled
    public static Account getAccounts() {
        return new account(name = 'test light account');
    }
    
    @AuraEnabled
    public static account saveRecord(account accountRecord) {
        return accountRecord;
    }
}
DemoPage.vfp

<apex:page sidebar="false">
    <apex:stylesheet value="{!URLFOR($Resource.SLDS0121, 'assets/styles/salesforce-lightning-design-system-vf.css')}" />
    <apex:includeLightning />
    <div id="containerLight">
        <div id="Lightning"/>
    </div>
    
    <script>
    	$Lightning.use("c:DemoApp", function(){
            $Lightning.createComponent("c:Demo",{},"Lightning",function(cmp){
            	
            });
        });
    </script>
</apex:page>
DemoApp.app

<aura:application access="GLOBAL" extends="ltng:outApp">
    <c:Demo />
</aura:application>

Please Update the Sample Code. Thanks




 
Naval Sharma4Naval Sharma4
Hi,

Update your helper method.
 
save : function(component, newAccRec) {
        var accR = [];
        accR.push(newAccRec);
        component.set('v.accounts', accR);
        var action = component.get("c.saveRecord");
        action.setParams({ 
            "accountRecord": newAccRec
        });
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (component.isValid() && state === "SUCCESS") {
                var rec = response.getReturnValue();
                console.log(rec);
            }
        });
        $A.enqueueAction(action);
    }

 
aks0011aks0011
Thanks for the reply Naval.

Yes I tried this too. But I think you are not running this code. please try and run this code in your environment and you will get a null returned.

So my concern is to get the recored in apex method and then returned to lightning component back just to see that it's being found or not.