Passing data from a Lightning input Text to Apex Controller and Save Records

//Apex Class :- contactcontroller 
public class contactcontroller
 {
         @AuraEnabled
         public static string save(string cnctDetails)
         {
             system.debug('cnctDetails----'+cnctDetails);
             ContactWC cnctObj =  (ContactWC)JSON.deserialize(cnctDetails,ContactWC.class);
             contact ct=new contact();
             ct.LastName=cnctObj.LastName;
             ct.Email=cnctObj.Email;
             ct.Phone=cnctObj.Phone;
             insert ct;
             return ct.id;
         }
         // ContactWC is Wrapper Class
         public class ContactWC
         {
             @AuraEnabled
             public string LastName;
             @AuraEnabled
             public string Email;
             @AuraEnabled
             public string Phone;
     }
 }

//Lightning Component :- ContactComponet

<aura:component controller=”contactcontroller” >

<aura:attribute name=”LastName” type=”String” default=””/>
<aura:attribute name=”Email” type=”String” default=””/>
<aura:attribute name=”Phone” type=”String” default=””/>

<form>
<lightning:input aura:id=”cnctLastName” type=”text” value=”{!v.LastName}” Name=”Last Name” label =”Last Name”/>
<lightning:input aura:id=”cnctEmail” type=”email” name=”email” label=”Email” value=”{!v.Email}” />
<lightning:input aura:id=”cnctPhone” type=”Phone” value=”{!v.Phone}” Name=”Phone” label=”Phone”/>
<lightning:button aura:id=”btncnctSave” label=”Save Contact Details” onclick=”{!c.savecontact}”/>
</form>

</aura:component>

//Lightning Component Controller :-
({
savecontact : function(component, event, helper)
{
debugger;
var lastNameval = component.get(“v.LastName”); // here,”LastName” is Component attributes and get value from lightning:input .

var Emailval = component.get(“v.Email”); // here,”Email” is Componentattributes and get value lightning:input .

var Phoneval = component.get(“v.Phone”); // here,”Phone” is Component attributes and get value lightning:input .

var d = new Object(); //here, Declare Object using JavaScript.

d.LastName = lastNameval;

d.Email = Emailval;

d.Phone = Phoneval;

var action = component.get(“c.save”); //save is apex controller method.

action.setParams({

“cnctDetails”: JSON.stringify(d) //here,passing parameters in apex controller and “cnctDetails” is a controller param name.

});
action.setCallback(this, function(a)
{

var state = a.getState();

if (state === “SUCCESS”)
{
var retVal = a.getReturnValue();
alert(“success” +retVal);
}
else
{
alert(“Failed”);
}
});
$A.enqueueAction(action) //calling Apex controller.

}

})

//Lightning Application :- ContactApplication
<aura:application >
<c:contactcomponent></c:contactcomponent>
</aura:application>

2 comments

Leave a Reply