Lightning Insert Parameter Using Apex:

This chapter explains about how to pass sobject data from lightning to apex and do an insert operation

There are 3 approach to pass data from lightning to apex to create sobject

Approach 1 :
Simply pass parameter to the apex method
Approach 2 :
Create Sobject in js and pass the Sobject to the apex
Here Sobject can be either standard or custom
Approach 3:
Create an JSON and pass it as string to apex

The below program shows an example of

Create an apex class and save it as ApexForSobjectInsert_Apex

/*


 * created by 		:		Shiva RV
 * Date			:		21-10-2018
 * Description		:		Contains differentTypes of Sobject Parameter passing from lightning 							to salesforce apex
*/

public class ApexForSobjectInsert {
	
    @AuraEnabled
    public static DemoSobjectWrapper demoAccount()
    {
 		 //Account newAccount=new Account(Name='ss',shivalight__email__c='ss@gmail.com',accountNumber='11');
		//insert newAccount;
       // return newAccount;
       return new DemoSobjectWrapper('ss','s@gma.com','12');
        
    }
    
    @AuraEnabled
    public static Account insertMethodType1(String accountName,String accountEmail,String accountNumber)
    {
        Account newAccount=new Account(Name=accountName,shivalight__email__c=accountEmail,accountNumber=accountNumber);
        insert newAccount;
        return newAccount;
    }
    
    @AuraEnabled
    public static Account insertMethodType2(Account acc)
    {
        Account acc1;
        try{
             System.debug(acc);
        	 System.debug(acc1);
        	 insert acc;
        }
        catch(Exception e)
        {
            System.debug(e);
        }
        return acc;
    }
   
    
    
    @AuraEnabled
    public static Account insertMethodType3(String accountWrapper)
    {
        System.debug(accountWrapper);
        DemoSobjectWrapper obj = (DemoSobjectWrapper)JSON.deserialize(accountWrapper, DemoSobjectWrapper.class);
		Account acc=new Account(Name=obj.accountName,shivalight__email__c=obj.accountEmail,accountNumber=obj.accountNumber);
        insert acc;
        return acc;
    }
    
    
}

Create the Lightning Event as below  and save it as  creatingSobjectComponent

<!--


 * created by 		:		Shiva RV
 * Date				:		22-10-2018
 * Description		:		Sobject creation using js and inserting using apex
       also inserting by passing paramter and using wrapper class for the same

  
-->
<aura:component controller="ApexForSobjectInsert" >
    
    <aura:attribute type="Account" name="newAccount"></aura:attribute>
    <aura:attribute type="String" name="accountName"></aura:attribute>
    <aura:attribute type="String" name="accountEmail"></aura:attribute>
    <aura:attribute type="String" name="accountNumber"></aura:attribute>
    <aura:attribute type="Account" name="insertedAccount"></aura:attribute>
    <aura:attribute type="Boolean" name="isResultObtained" default="false"></aura:attribute>
    <aura:attribute type="String" name="MethodType"></aura:attribute>
    <aura:attribute type="String" name="MethodDescription"></aura:attribute>

    <lightning:input name="accountName" label="Account Name" type="Text" aura:id="accountName" />
    <lightning:input name="accountEmail" label="Account Email" type="Email" aura:id="accountEmail" />
    <lightning:input name="accountNumber" label="Account Number" type="Number" aura:id="accountNumber" />
    <lightning:Button name="Method 1" label="Simple Parameter Passing" onclick="{!c.simpleParameterType}"></lightning:Button>
    <lightning:Button name="Method 2" label="Create Sobject and Passing" onclick="{!c.sobjectPassing}"></lightning:Button>
    <lightning:Button name="Method 3" label="Create Wrapper class and Passing" onclick="{!c.wrapperClassPassing}"></lightning:Button>
 
    <aura:If isTrue="{!v.isResultObtained}">
    <div class="demo-only" style="padding: 0.5rem; background: rgb(22, 50, 92);">
  	<div class="slds-text-color_inverse slds-text-align_center"><b>{!v.MethodType}</b> {!v.MethodDescription}</div>

	</div>
    <table class="slds-table slds-table_cell-buffer slds-table_bordered">
  <thead>
    <tr class="slds-line-height_reset">
      <th class="slds-text-title_caps" scope="col">
        <div class="slds-truncate" title="Account Id">Account Id</div>
      </th>
      <th class="slds-text-title_caps" scope="col">
        <div class="slds-truncate" title="Account Name">Account Name</div>
      </th>
      <th class="slds-text-title_caps" scope="col">
        <div class="slds-truncate" title="Account Email">Account Email</div>
      </th>
        <th class="slds-text-title_caps" scope="col">
        <div class="slds-truncate" title="Account Number">Account Number</div>
      </th>
      </tr>
        </thead>
        <tbody>
    	<tr class="slds-hint-parent">
      	<th data-label="Account Id" scope="row">
        <div class="slds-truncate" title="Cloudhub"><a href="javascript:void(0);" tabindex="-1">{!v.insertedAccount.Id}</a></div>
      	</th>
        <th data-label="Account Name" scope="row">
        <div class="slds-truncate" title="Cloudhub"><a href="javascript:void(0);" tabindex="-1">{!v.insertedAccount.Name}</a></div>
      	</th>
        <th data-label="Account Email" scope="row">
        <div class="slds-truncate" title="Cloudhub"><a href="javascript:void(0);" tabindex="-1">{!v.insertedAccount.shivalight__email__c}</a></div>
      	</th>
        <th data-label="Account Number" scope="row">
        <div class="slds-truncate" title="Cloudhub"><a href="javascript:void(0);" tabindex="-1">{!v.insertedAccount.AccountNumber}</a></div>
      	</th>
        </tr>
        </tbody>
        </table>
        </aura:If>
</aura:component>

ParamEventFiringChildComp_Js Js Controller Code:
({
    
   //for passing parameter type 1 
   //simple fetch the values and pass it as simple type to apex
	simpleParameterType : function(component, event, helper) {
       	var accountName=component.find("accountName").get("v.value");
        var accountEmail=component.find("accountEmail").get("v.value");
		var accountNumber=component.find("accountNumber").get("v.value");
        component.set("v.isResultObtained",false);
        component.set("v.MethodType","Method Type 1");
		component.set("v.MethodDescription"," (Simple parameter passing)");
		helper.insertSobjectHelper1(component,accountName,accountEmail,accountNumber);
	},
    
    //for passing parameter type 2 
    //create sobject and pass it to apex method
    sobjectPassing : function(component, event, helper) {
		var accountName=component.find("accountName").get("v.value");
        var accountEmail=component.find("accountEmail").get("v.value");
		var accountNumber=component.find("accountNumber").get("v.value");
		component.set("v.isResultObtained",false);
        component.set("v.MethodType","Method Type 2");
        component.set("v.MethodDescription"," (Sobject creation and passing)");
        var newAccount={"sobjectType":"Account", "Name":accountName,"shivalight__email__c":accountEmail,"AccountNumber":accountNumber};
        helper.insertSobjectHelper2(component,newAccount);
  
	},
    //for passing parameter type 3 
    //must serialise the json and pass it to apex, there it must be deseralised and used
    wrapperClassPassing : function(component, event, helper) {
		var accountName=component.find("accountName").get("v.value");
        var accountEmail=component.find("accountEmail").get("v.value");
		var accountNumber=component.find("accountNumber").get("v.value");
        console.log(accountName+"  "+accountEmail+" "+accountNumber);
        var newAccountWrapper={"accountName":accountName,
                        "accountEmail":accountEmail,
                        "accountNumber":accountNumber
                       };
		component.set("v.isResultObtained",false);
        component.set("v.MethodType","Method Type 3");
        component.set("v.MethodDescription"," (Wrapper json serialisation)");
        helper.insertSobjectHelper3(component,JSON.stringify(newAccountWrapper));
	},
})
 
ParamEventFiringChildComp_Js Helper Controller Code:
({
	insertSobjectHelper1 : function(component,accountName,accountEmail,accountNumber) {
	 var action= component.get("c.insertMethodType1");
     action.setParams({"accountName" : accountName,
                       "accountEmail" : accountEmail,
                       "accountNumber" : accountNumber
                      });
     action.setCallback(this, function(response)
     {
     	var state = response.getState();
        if (state === "SUCCESS") 
        {
        	console.log(response.getReturnValue());
            component.set("v.isResultObtained",true);

        	component.set("v.insertedAccount",response.getReturnValue());
        }
        else
        {
        }    
     });
     $A.enqueueAction(action);	
	},
    
    insertSobjectHelper2 : function(component,newAccount) {
	 var action= component.get("c.insertMethodType2");
     action.setParams({"acc" : newAccount
                      });
     action.setCallback(this, function(response)
     {
     	var state = response.getState();
        if (state === "SUCCESS") 
        {
        	console.log(response.getReturnValue());
            component.set("v.isResultObtained",true);
        	component.set("v.insertedAccount",response.getReturnValue());
        }
        else
        {
        }    
     });
     $A.enqueueAction(action);	
	},
    
    insertSobjectHelper3 : function(component,newWrapper) {
	 var action= component.get("c.insertMethodType3");
     console.log("in helper3 method "+newWrapper);
     action.setParams({"accountWrapper" : newWrapper
                      });
     action.setCallback(this, function(response)
     {
     	var state = response.getState();
        if (state === "SUCCESS") 
        {
        	console.log(response.getReturnValue());
            component.set("v.isResultObtained",true);
        	component.set("v.insertedAccount",response.getReturnValue());
        }
        else
        {
        }    
     });
     $A.enqueueAction(action);	
	},

    
})
Below is the hello world App code:
<!--


 * created by 		:		Shiva RV
 * Date				:		13-10-2018
 * Description		:		Hello World Lighting App
  
-->

<aura:application extends="force:slds">
<!--this is the lightning app where you can place html codes , associate js code
		also can embed lightning component to it -->
  
 <!--Sobject insert from lightning varieties , must be create-->
    <c:creatingSobjectComponent></c:creatingSobjectComponent>
</aura:application>
Output:

 

Key Notes :
*The output shows the result of each insert operation
*The above program shows  the different ways of passing data from lightning to apex method
*Wrapper class approach is used generally for complex logics