Save and bind Data in Picklist dynamically in Lightning Salesforce

/**
*  Class Name      : AccountClass
*  Description     : Create Account and Get Data from Account Dynamically and Data bind in Picklist.
**/
Public class AccountClass{
@AuraEnabled
public static Account SaveAccountDetails(Account objAccount)
{
try
{
system.debug('<<<<<objAccount>>>>>'+objAccount);
insert objAccount; 
system.debug('<<<<<Account ID>>>>>'+objAccount.id);
return objAccount;
} 
catch(DmlException ex)
{
system.debug('>>>>>SaveAccountDetails Error>>>>>> ' + ex.getMessage() + ' >>>>Line Number>>>> ' + ex.getLineNumber());
throw new AuraHandledException('SaveAccountDetails Error: ' + ex.getMessage()); 
}

}

@AuraEnabled 
public static List<String> getPicklistvalues(String objectName, String field_apiname){
List<String> pickListValuesList = new List<String>();
try
{
Schema.SObjectType convertToObj = Schema.getGlobalDescribe().get(objectName);
system.debug('<<<<convertToObj>>>>' +convertToObj);
Schema.DescribeSObjectResult res = convertToObj.getDescribe();
system.debug('<<<<res>>>>' +res);
Schema.DescribeFieldResult fieldResult = res.fields.getMap().get(field_apiname).getDescribe();
system.debug('<<<<fieldResult>>>>' +fieldResult);
List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();
system.debug('<<<<ple>>>>' +ple);
for( Schema.PicklistEntry pickListVal : ple){
pickListValuesList.add(pickListVal.getLabel());
}
}
catch(Exception ex)
{
system.debug('>>>>>AccountClass getPicklistvalues Error>>>>>> ' + ex.getMessage() + ' >>>>Line Number>>>> ' + ex.getLineNumber());
}
system.debug('<<<<pickListValuesList>>>>' +pickListValuesList);
return pickListValuesList;
}

}
<!--
* Component Name : "AccPicklist"
-->
<aura:component controller="AccountClass">
<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:handler name="init" value="{!this}" action="{!c.doInit}" />
<aura:method name="validatePicklistField" action="{!c.validatePicklistValue}" access="public"/>
<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>
<!--
AccPicklistController.js
-->

({
doInit : function(component, event, helper) {
debugger;
var action = component.get("c.getPicklistvalues");
action.setParams({
objectName: component.get("v.sObjectName"),
field_apiname: component.get("v.fieldName")
});
action.setCallback(this, function(response) { 
debugger;
var state = response.getState();
if(state === 'SUCCESS'){
var respnse= response.getReturnValue();
component.set("v.picklistValues", respnse);
}
});
$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();
}
}
})
<!--
* Component Name : AccountCmp
-->

<aura:component controller="AccountClass" implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" >
<aura:handler name="init" value="{!this}" action="{!c.doInit}" /> 
<aura:attribute name="newAccount" type="Account" default="{'sobjectType':'Account'}"/>
<aura:attribute name= "accType" type="String" default="Prospect"/>
<aura:attribute name= "accTypePicklist" type="String[]" /> 
<aura:attribute name= "accPriority" type="String" default="High"/>


<!-- aura handler with waiting and donewaiting events--> 
<aura:handler event="aura:waiting" action="{!c.showSpinner}"/>
<aura:handler event="aura:doneWaiting" action="{!c.hideSpinner}"/>
<!--create a Spinner component attributs -->
<aura:attribute name="Spinner" type="boolean" default="false"/>


<!--loading spinner start... style=Brand Medium (blue dots)-->
<aura:if isTrue="{!v.Spinner}">
<div aura:id="spinnerId" class="slds-spinner_container">
<div class="slds-spinner--brand slds-spinner slds-spinner--large slds-is-relative" role="alert">
<span class="slds-assistive-text">Loading</span>
<div class="slds-spinner__dot-a"></div>
<div class="slds-spinner__dot-b"></div>
</div>
</div>
</aura:if>
<!-- Loading spinner end--> 


<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"/> 
Account Information
</span>
</button>
</h3> 
</lightning:layoutItem>
</lightning:layout>

<div class="slds-box">
<lightning:layout> 
</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.newAccount.Name}" label="Account Name" aura:id="AccountNameId" />
</lightning:layoutItem> 
</lightning:layout>

<lightning:layout>
<lightning:layoutItem flexibility="auto" size="6" smallDeviceSize="6" mediumDeviceSize="6" largeDeviceSize="6" padding="horizontal-large">
<c:AccPicklist sObjectName="Account"
fieldName="Type"
aura:id="accTypeID"
picklistvalue="{!v.newAccount.Type}"
fieldLabel="Type" 
required = "true"/>

</lightning:layoutItem> 
</lightning:layout>


<lightning:layout>
<lightning:layoutItem flexibility="auto" size="6" smallDeviceSize="6" mediumDeviceSize="6" largeDeviceSize="6" padding="horizontal-large"> 
<c:AccPicklist sObjectName="Account"
fieldName="Industry"
aura:id="accIndustryID"
picklistvalue="{!v.newAccount.Industry}"
fieldLabel="Industry"
required = "true"/>
</lightning:layoutItem> 
</lightning:layout>

<lightning:layout>
<lightning:layoutItem flexibility="auto" size="6" smallDeviceSize="6" mediumDeviceSize="6" largeDeviceSize="6" padding="horizontal-large"> 
<lightning:select label="Customer Priority">
<option value="">--Select--</option>
<aura:iteration items="{!v.accTypePicklist}" var="accPriorityVal">
<option value="{!accPriorityVal}" selected="{!accPriorityVal==v.accPriority}">{!accPriorityVal}</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">
<lightning:input type="text" value="{!v.newAccount.Description}" label="Description" aura:id="DescriptionId" />
</lightning:layoutItem>
</lightning:layout>
<br/> 
<lightning:button aura:id="btnSubmit" variant="brand" label="Submit" class="slds-m-left_large" onclick="{!c.createAccnt}" />
</div>
</aura:component>
<!--
AccCmp Controller.js
-->
({

doInit: function (component, event, helper){
debugger;
helper.fetchAccPriorityPicklist(component); //here, fetchcasePriorityPicklist() calling from helper.js 

},
createAccnt : function(component, event, helper) { 
debugger; 
component.set("v.newAccount.CustomerPriority__c",component.get("v.accPriority"));
var accObj = component.get("v.newAccount");
console.log('<<<accObj>>>>' +accObj);
helper.validate(component, event, helper, 'AccountNameId'); //for INPUT "text" TYPE
if($A.util.isEmpty(accObj.Type) || $A.util.isEmpty(accObj.Industry)){ 
helper.validatePicklist(component, event, helper, 'accTypeID'); //for picklist type
helper.validatePicklist(component, event, helper, 'accIndustryID');
return;
} 
var action = component.get("c.SaveAccountDetails");
action.setParams({ 
objAccount: accObj
}); 
action.setCallback(this, function(response) {
var state = response.getState();
console.log('<<<state>>>>' +state);
if (state === "SUCCESS"){
var respVal=response.getReturnValue();
console.log('<<<respVal>>>>' +respVal);
var newLine = "\r\n";
var messg="The record has been save successfully!!! ";
messg=messg+newLine;
messg=messg+ " Your Account is " + respVal.Id;
alert(messg); 
window.location.reload(); 
}
else if(state === "ERROR")
{
var error = response.getError();
alert(error[0].message); 

}
});
$A.enqueueAction(action)
},
// this function automatic call by aura:waiting event 
showSpinner: function(component, event, helper) {
// make Spinner attribute true for display loading spinner 
component.set("v.Spinner", true); 
}, 
// this function automatic call by aura:doneWaiting event 
hideSpinner : function(component,event,helper){
// make Spinner attribute to false for hide loading spinner 
component.set("v.Spinner", false);
}

})

<!--
AccCmp Helper.js
-->
({

fetchAccPriorityPicklist : function(component){
var action = component.get("c.getPicklistvalues");
action.setParams({
'objectName': "Account",
'field_apiname': "CustomerPriority__c",
});
action.setCallback(this, function(a) {
var state = a.getState();
if (state === "SUCCESS"){
component.set("v.accTypePicklist", a.getReturnValue());
}
});
$A.enqueueAction(action);
},
validate : function(component, event, helper, paramId){
debugger;
var inputField = component.find(paramId);
var value = inputField.get("v.value");
if($A.util.isEmpty(value)){
inputField.setCustomValidity("Required");
}else{
inputField.setCustomValidity("");
}
inputField.reportValidity();
},
validatePicklist : function(component, event, helper, paramId){
debugger;
var cmp= component.find(paramId);
cmp.validatePicklistField(); // calling from AccPicklist component
}

})
Lightning Application:- AccApp
<aura:application extends="force:slds" >
<c:AccountCmp/>
</aura:application>
OutPut

Leave a Reply