Insert Records in Lightning Components Salesforce using JSON.parse,Append Data and pass Data in apex Controller

// Apex Controller: StudentController
public class StudentController {
@AuraEnabled
public static Student__c SaveStudentDetails(Student__c stndObj){
try
{
system.debug('>>>>>>>stndObj>>>>'+stndObj);
insert stndObj;
return stndObj;
}
catch(DmlException ex)
{
System.debug('The following exception has occurred: ' + ex.getMessage());
throw new AuraHandledException('Something went wrong: ' + ex.getMessage());
}


}

@AuraEnabled
public static List<String> getPickListValuesIntoList(String objectType, String selectedField){
List<String> pickListValuesList = new List<String>();
Schema.SObjectType convertToObj = Schema.getGlobalDescribe().get(objectType);
Schema.DescribeSObjectResult res = convertToObj.getDescribe();
Schema.DescribeFieldResult fieldResult = res.fields.getMap().get(selectedField).getDescribe();
List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();
for( Schema.PicklistEntry pickListVal : ple){
pickListValuesList.add(pickListVal.getLabel());
}
return pickListValuesList;
}

}
//Lightning Component: StudentPicklistComponent
<aura:component controller="StudentController">
<aura:attribute name="sObjectName" type="String" />
<aura:attribute name="fieldName" type="String" />
<aura:attribute name="fieldLabel" type="String"/>
<aura:attribute type= "boolean" name= "required" default="false"/>
<aura:attribute name="picklistValues" type="String[]" />
<aura:attribute name="picklistvalue" type="String"/>
<aura:method name="validatePicklistField" action="{!c.validatePicklistValue}" access="public"/>
<aura:handler name="init" value="{!this}" action="{!c.doInit}" />
<lightning:layout>
<lightning:layoutItem size="12" smallDeviceSize="12" mediumDeviceSize="12" largeDeviceSize="12" flexibility="auto">
<lightning:select label="{!v.fieldLabel}" value="{!v.picklistvalue}" class="font" aura:id = "PicklistField" required = "{!v.required}">
<option value="" >--Select--</option>
<aura:iteration items="{!v.picklistValues}" var="val">
<option value="{!val}">{!val}</option>
</aura:iteration>
</lightning:select>
</lightning:layoutItem>
</lightning:layout>
</aura:component>
//StudentPicklistComponent Controller.js
({
doInit : function(component, event, helper) {
var action = component.get("c.getPickListValuesIntoList");
action.setParams({
objectType: component.get("v.sObjectName"),
selectedField: component.get("v.fieldName")
});
action.setCallback(this, function(response) {
var state = response.getState();
if(state === 'SUCCESS'){
component.set("v.picklistValues", response.getReturnValue());
}
});
$A.enqueueAction(action);
},
validatePicklistValue : function(component) {
var inputField=component.find('PicklistField');
if($A.util.isEmpty(component.get('v.picklistvalue'))){
$A.util.addClass(inputField, "slds-has-error");
inputField.showHelpMessageIfInvalid();
}
}
})
//Lightning Component :- StudentComponent
<aura:component  Controller="StudentController" implements="force:appHostable,lightning:isUrlAddressable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction,lightning:actionOverride" access="global">
<aura:handler name="init" value="{!this}" action="{!c.doInit}" />
<aura:attribute name="Students" type="Student__c" default="{'sobjectType':'Student__c'}"/>
<aura:attribute name= "statePicklistVal" type="String[]" />
<aura:attribute name= "StateSelected" type="String" default="NEW DELHI"/>
<lightning:layout>
<lightning:layoutItem size="12" smallDeviceSize="12" mediumDeviceSize="12" largeDeviceSize="12">
<h3 class="slds-section__title header_border_radius">
<button class="slds-button slds-section__title-action header_border_radius" aria-expanded="true" aria-controls="expando-unique-id">
<span title="Section Title" class="slds-truncate">
<lightning:icon iconName="standard:location" size="small" alternativeText="Related Contacts" class="slds-m-around_small"/>
Student Information
</span>
</button>
</h3>
</lightning:layoutItem>
</lightning:layout>

<div class="slds-box">
<lightning:layout>
<lightning:layoutItem flexibility="auto" size="6" smallDeviceSize="6" mediumDeviceSize="6" largeDeviceSize="6" padding="horizontal-large">
<lightning:input type="text" value="{!v.Students.Name__c}" label="Student Name" aura:id="stndNameId" required="true"/>
</lightning:layoutItem>
</lightning:layout>


<lightning:layout>
<lightning:layoutItem flexibility="auto" size="6" smallDeviceSize="6" mediumDeviceSize="6" largeDeviceSize="6" padding="horizontal-large">
<lightning:input type="text" value="{!v.Students.Mobile_No__c}" label="Mobile Number" aura:id="stndMbId" required="true"/>
</lightning:layoutItem>
</lightning:layout>


<lightning:layout>
<lightning:layoutItem flexibility="auto" size="6" smallDeviceSize="6" mediumDeviceSize="6" largeDeviceSize="6" padding="horizontal-large">
<lightning:input type="text" value="{!v.Students.Email_Address__c}" label="Email Address" aura:id="StndEmailID" required="true"/>
</lightning:layoutItem>
</lightning:layout>


<!--lightning:layout>
<lightning:layoutItem size="6" smallDeviceSize="6" mediumDeviceSize="6" largeDeviceSize="6" padding="horizontal-large">
<lightning:select label="State" value="{!v.statePicklistVal}" >
<aura:iteration items="{!v.StateSelected}" var="s">
<option value="{!s}">{!s}</option>
</aura:iteration>
</lightning:select>
</lightning:layoutItem>
</lightning:layout-->


<lightning:layout>
<lightning:layoutItem size="6" smallDeviceSize="6" mediumDeviceSize="6" largeDeviceSize="6" padding="horizontal-large">
<lightning:select label="State" value="{!v.StateSelected}">
<aura:iteration items="{!v.statePicklistVal}" var="val">
<option value="{!val}">{!val}</option>
</aura:iteration>
</lightning:select>
</lightning:layoutItem>
</lightning:layout>




<lightning:layout>
<lightning:layoutItem flexibility="auto" size="6" smallDeviceSize="6" mediumDeviceSize="6" largeDeviceSize="6" padding="horizontal-large">
<c:StudentPicklistComponent aura:id="MailTypeid"
sObjectName="Student__c"
fieldName="Mail_Type__c"
picklistvalue="{!v.Students.Mail_Type__c}"
fieldLabel="Mail Type" required="true"/>

</lightning:layoutItem>
</lightning:layout>
</div>
<aura:if isTrue= "{!(v.Students.Mail_Type__c != 'E-Mail')}">
<lightning:layout>
<lightning:layoutItem size="12" smallDeviceSize="12" mediumDeviceSize="12" largeDeviceSize="12">
<h3 class="slds-section__title header_border_radius">
<button class="slds-button slds-section__title-action header_border_radius" aria-expanded="true" aria-controls="expando-unique-id">
<span title="Section Title" class="slds-truncate">
<lightning:icon iconName="standard:location" size="small"
alternativeText="Related Contacts" class="slds-m-around_small"/>
Student Address Information
</span>
</button>
</h3>
</lightning:layoutItem>
</lightning:layout>
<div class="slds-box">
<lightning:layout>

<lightning:layoutItem flexibility="auto" size="6" smallDeviceSize="6" mediumDeviceSize="6" largeDeviceSize="6" padding="horizontal-large">
<lightning:input type="text" value="{!v.Students.Mailing_Street__c}" label="Mailing Street" aura:id="StudentMailiongStreetId" />
</lightning:layoutItem>
</lightning:layout>


<lightning:layout>
<lightning:layoutItem flexibility="auto" size="6" smallDeviceSize="6" mediumDeviceSize="6" largeDeviceSize="6" padding="horizontal-large">
<lightning:input type="text" value="{!v.Students.Mailing_City__c}" label="Mailing City" aura:id="MailingCityId" />
</lightning:layoutItem>
</lightning:layout>


<lightning:layout>
<lightning:layoutItem flexibility="auto" size="6" smallDeviceSize="6" mediumDeviceSize="6" largeDeviceSize="6" padding="horizontal-large">
<lightning:input type="text" value="{!v.Students.MailingStateProvince__c}" label="Mailing State/Province" aura:id="MailingStateid" />
</lightning:layoutItem>
</lightning:layout>


<lightning:layout>
<lightning:layoutItem flexibility="auto" size="6" smallDeviceSize="6" mediumDeviceSize="6" largeDeviceSize="6" padding="horizontal-large">
<lightning:input type="text" value="{!v.Students.Mailing_Zip_Postal_Code__c}" label="Mailing Zip/Postal Code" aura:id="MailingZipid" />
</lightning:layoutItem>
</lightning:layout>

</div>

</aura:if>

<lightning:layout>
<lightning:layoutItem size="12" smallDeviceSize="12" mediumDeviceSize="12" largeDeviceSize="12">
<h3 class="slds-section__title header_border_radius">
<button class="slds-button slds-section__title-action header_border_radius" aria-expanded="true" aria-controls="expando-unique-id">
<span title="Section Title" class="slds-truncate">
<lightning:icon iconName="standard:location" size="small"
alternativeText="Related Contacts" class="slds-m-around_small"/>
Student Description
</span>
</button>
</h3>
</lightning:layoutItem>
</lightning:layout>
<div class="slds-box">
<lightning:layout>
<lightning:layoutItem flexibility="auto" size="6" smallDeviceSize="6" mediumDeviceSize="6" largeDeviceSize="6" padding="horizontal-large">
<lightning:input type="text" value="{!v.Students.Description__c}" label="Description" aura:id="DescriptionId" />
</lightning:layoutItem>
</lightning:layout>
<br/>
<div>
<lightning:button aura:id="btnSubmit" variant="brand" label="Submit" onclick="{!c.studentDetails }"/>
</div>
</div>


</aura:component>
//StudentComponentController.js
({
doInit: function (component, evt, helper){
debugger;
var action = component.get("c.getPickListValuesIntoList");
action.setParams({
'objectType': "Student__c",
'selectedField': "State__c",
});
action.setCallback(this, function(a) {
debugger;
var state = a.getState();
if (state === "SUCCESS"){
var xx=a.getReturnValue();
component.set("v.statePicklistVal", a.getReturnValue());
}
});
$A.enqueueAction(action);

},
studentDetails : function(component, event ,helper){
debugger;
helper.validate(component, event, helper, 'stndNameId'); // here, Lightning Validation Use on Input Text.
helper.validate(component, event, helper, 'stndMbId'); // here, Lightning Validation Use on Input Text.
helper.validate(component, event, helper, 'StndEmailID'); // here, Lightning Validation Use on Input Text.
helper.validatePicklist(component, event, helper, 'MailTypeid'); // here, Lightning Validation Use on Picklist Field.
var stnds = component.get("v.Students");

var jsondata= JSON.stringify(stnds); // Here, Converted to Json String.

var stateVal=component.get("v.StateSelected"); // Here, get Value from aura attributes.

var parsedData = JSON.parse(jsondata); // Here, Converted JsonString to Json Object.

parsedData['State__c'] = stateVal; // Here, Append Data in Json Object.

//var myJsonObject = JSON.stringify(parsedData); //change back to string

//console.log('<<<<myJsonObject>>>>'+myJsonObject);

var action = component.get("c.SaveStudentDetails");
action.setParams({
stndObj: parsedData // Here, Pass the Json Object Data in Apex Controller
});
action.setCallback(this, function(response) {
debugger;
var state = response.getState();
if (state === "SUCCESS") {
//component.set("v.Students", response.getReturnValue());
alert("The record has been Save successfully.");
window.location.reload();
}
else if( (state === "ERROR"))
{
var error = response.getError();
alert(error[0].message);
}
});
$A.enqueueAction(action)
}
})

//Student Component helper.Js

({
validate : function(component, event, helper, CmpId){
var inputField = component.find(CmpId);
var value = inputField.get("v.value");
if($A.util.isEmpty(value)){
inputField.setCustomValidity("Required!!!");
}else{
inputField.setCustomValidity("");
}
inputField.reportValidity();
},
validatePicklist : function(component, event, helper, CmpId){
if($A.util.isEmpty(component.get('v.Students.Mail_Type__c'))){
var cmp= component.find('MailTypeid');
cmp.validatePicklistField();
}
},
})

//Lightning App:- StudentAPP

<aura:application extends="force:slds">
<c:StudentComponent></c:StudentComponent>
<!--c:StudentPicklistComponent></c:StudentPicklistComponent-->
</aura:application>
 
Validation OutPut:-
Without Validation OutPut:-

Leave a Reply