Save Form With Multiple Picklist fields in Lightning Component

To understand the emphasis placed on multiple picklist fields in this post – save form with multiple picklist fields in Lightning Component, I recommend that you go through my post Create Form with Picklist fields in Lightning Component where I explained the need for a picklist service component and both Apex and client-side controllers.

Use force:recordData

The Lightning Data Service (LDS) uses an object named force:recordData to perform CRUD (Create, Read, Update, and Delete) interactions on records. In this post we are going to use recordId, targetRecord, fields, and mode attributes of force:recordData. The force:recordData has the VIEW mode or EDIT mode and because we need to create a record, it will be in EDIT mode If a value is assigned to the recordId attribute, LDS works behind the scenes to retrieves either the entire record or the requested fields.. The resulting fields are stored in the targetFields attribute; in ourcase in this post schRecord.

Below is the Component that uses the force:recordData and the multiple picklist fields. Note that with force:recordData, you must provide your own labels.

<!--submitNewSchool.cmp-->
<aura:component implements="flexipage:availableForRecordHome,force:hasRecordId" access="global">
     
 <aura:attribute name="picklistValues1" type="Object" />
 <aura:attribute name="picklistValues2" type="Object" />
 <aura:attribute name="schRec" type="School__c" />
 <aura:attribute name="modal1" type="String" default="New" />
    <force:recordData aura:id="schoolRecord"
                    recordId="{!v.recordId}"
                    targetFields="{!v.schRec}"
                    fields="Id, Name, District__c,Type__c,         Principal__c, School_Category__c"
                      mode="EDIT" />
      
    <aura:handler name="init" value="{!this}" action="{!c.doInit}" />
     
<c:SchoolPicklists sObjectName="School__c" fieldName="Type__c" picklistValues="{!v.picklistValues1}" />
<c:SchoolPicklists sObjectName="School__c" fieldName="School_Category__c" picklistValues="{!v.picklistValues2}" />

 <div aura:id="editDialog" role="dialog" tabindex="-1" aria-labelledby="header43" class="slds-modal slds-fade-in-open">
<div class="slds-modal__container">
<div class="slds-modal__header">
<h2 class="slds-text-heading--medium">Create {!v.modal1} Record</h2>
</div>
<div class="slds-modal__content slds-p-around--medium slds-grid slds-wrap ">
<lightning:input aura:id="schName" name="schName" label="School Name" value="{!v.schRec.Name}" required="true" class="slds-size--1-of-1 slds-p-horizontal_x-small" />
<lightning:input aura:id="schDistrict" name="schDistrict" label="District" value="{!v.schRec.District__c}" class="slds-size--1-of-2 slds-p-horizontal_x-small" />
 <lightning:input aura:id="schPrincipal" name="schPrincipal" label="Principal" value="{!v.schRec.Principal__c}" class="slds-size--1-of-2 slds-p-horizontal_x-small" />

<lightning:select aura:id="schType" name="schType" label="Type" value="{!v.schRec.Type__c}" class="slds-size--1-of-2 slds-p-horizontal_x-small">
<aura:iteration items="{!v.picklistValues1}" var="item">
   <option value="{!item}">{!item}</option>
</aura:iteration>
</lightning:select>

<lightning:select aura:id="schCategory" name="schCategory" label="Category" value="{!v.schRec.School_Category__c}" class="slds-size--1-of-2 slds-p-horizontal_x-small">
 <aura:iteration items="{!v.picklistValues2}" var="item">
  <option value="{!item}">{!item}</option>
 </aura:iteration>
 </lightning:select>                
   </div>
 <div class="slds-modal__footer">                
 <lightning:button variant="neutral" onclick="{!c.handleCancel}" label="Cancel" />
 <lightning:button variant="brand" label="Submit" onclick="{!c.handleSaveRecord}" />
  </div>
  </div>
</div>
<div aura:id="overlay" class="slds-backdrop slds-backdrop--open">
</div>
</aura:component>

In this sumitNewSchool.cmp, to be able to save form with multiple picklist fields in Lightning Component, the value attributes for lightning:input, lightning:select and any other components used must be specified.

For the Controller – sumitNewSchoolController.js

({
	doInit : function(component, event, helper) {
        var recId = component.get("v.recordId");
    if (recId) {
        component.set("v.modal1", "Edit");
    }    
	if (!recId) {
    component.find("schoolRecord").getNewRecord(
        "School__c",
        null,
        false,
        $A.getCallback(function() {
          var rec = component.get("v.schRec");
          var error = component.get("v.recordError");
       if (error || (rec === null)) {
      console.log("Error initializing the record: " + error);
         return;
            }
        })
    ); 
 }
},
    handleCancel: function(component, event, helper) {
    var recId = component.get("v.recordId");
    if (!recId) {
        var homeEvent = $A.get("e.force:navigateToObjectHome");
        homeEvent.setParams({
            "scope": "School__c"
        });
        homeEvent.fire();
    } else {
        helper.navigateTo(component, recId);
    }
},
    handleSaveRecord : function(component, event, helper) {        
    component.set("v.schRec.Name", component.find('schName').get("v.value"));    
   component.set("v.schRec.District__c", component.find('schDistrict').get("v.value"));
    component.set("v.schRec.Principal__c", component.find('schPrincipal').get("v.value"));
    component.set("v.schRec.Type__c", component.find('schType').get("v.value"));
    component.set("v.schRec.School_Category__c", component.find('schCategory').get("v.value"));

    var scRec = component.find("schoolRecord");
    scRec.saveRecord($A.getCallback(function(response) {
        console.log(response.state);
        var resultsToast = $A.get("e.force:showToast");
        if (response.state === "SUCCESS") {
           resultsToast.setParams({
              "title": "Saved",
              "message": "The record was successfully saved."
            });
            resultsToast.fire();
        } else if (response.state === "ERROR") {
        console.log('Error: ' + JSON.stringify(response.error));
        resultsToast.setParams({
            "title": "Error",
            "message": "There was an error saving the record: " + JSON.stringify(result.error)
        });
        resultsToast.fire();        
    } else {
console.log('Unknown problem, state: ' + result.state + ', error: ' + JSON.stringify(result.error));
    }         
 }));
}
})

The getNewRecord of force:recordData takes four parameters. The first parameter is School__c, that is the API name for the sObject of the record. The second parameter is for the recordTypeId which is set to null. The third parameter which is either true or false depending on whether or not to load the record template from the client-side cache and last one is the callback which checks for an error.

Also note that when you use force:recordData, you need to call the saveRecord function.

The Helper – submitNewSchoolHelper.js

({
    navigateToSObj: function(component, recId) {
        var navEvent = $A.get("e.force:navigateToSObject");
        navEvent.setParams({
            "recordId": recId
        });
        navEvent.fire();
    }
})

Thanks for coming by. Don’t forget to contact me, if you have any question

Reference

Lightning Aura Components Developer Guide

This Post Has One Comment

Leave a Reply