Create a Form with Picklist fields in Lightning Component

To create a form,

To create a Lightning Component, follow these steps:

  1. In the Developer Console, choose File | New | Lightning Component.
  2. Give the component a name, for example, schoolForm (because I’m using a custom object – School__c in this post).
  3. Under Component Configuration, select Lightning Record Page and click Submit

To create a form with picklist fields in Lightning Component,

While creating a form in Lightning Component, there are many assumptions you have especially if you are coming from Visualforce environment. However, in Visualforce, the controllers are sever-side which means that the data you request for is pulled from the server. Unlike the LC, the controllers client-side. There are logics you have to write to pull data like the picklist values of a given field into your form or page.

In this post, to create a form that has picklist fields,

Create a component for example schoolForm.cmp. Add the code below

<aura:component implements="flexipage:availableForRecordHome,force:hasRecordId" access="global" >
   <!--Two aura attributes defined for the 2 picklist fields--> 
    <aura:attribute name="picklistValues1" type="Object" />
    <aura:attribute name="picklistValues2" type="Object" />

   <c:SchoolPicklists sObjectName="School__c" fieldName="Type__c" picklistValues="{!v.picklistValues1}" />
   <c:SchoolPicklists sObjectName="School__c" fieldName="School_Category__c" picklistValues="{!v.picklistValues2}" />
<lightning:input aura:id="schName" name="schName" label="School Name" required="true" />
<lightning:input aura:id="" name="schDistrict" label="District" />
<lightning:input aura:id="schPhone" name="schPhone" label="Phone" />
<lightning:select aura:id="schType" name="schType" label="Type">
        <aura:iteration items="{!v.picklistValues1}" var="item">
    <option value="{!item}">{!item}</option>
</aura:iteration>

</lightning:select>
<lightning:input aura:id="schPrincipal" name="schPrincipal" label="Principal" />
<lightning:select aura:id="schCategory" name="schCategory" label="Category">
<aura:iteration items="{!v.picklistValues2}" var="items">
    <option value="{!items}">{!items}</option>
</aura:iteration>

</lightning:select>
<lightning:button variant="neutral" label="Cancel" />
<lightning:button variant="brand" label="Submit" />

</aura:component>

If you don’t want to have an error while saving the SchoolForm.cmp code, you need to create the Picklist component because the code calls the component which does not exist yet. Before creating the component, create an Apex Controller that will populate the picklist fields with the values. Call it PicklistApexController. Below is the Apex code

public class PicklistApexController {
 @AuraEnabled        
 public static List getPickListValues(String objectType, String selectedField) {
     List pkListValues = new List();
     Schema.SObjectType obj = Schema.getGlobalDescribe().get(objectType);
     Schema.DescribeSObjectResult res = obj.getDescribe();
     Schema.DescribeFieldResult result = res.fields.getMap().get(selectedField).getDescribe();
     List pkle = result.getPicklistValues();
     for( Schema.PicklistEntry pklVal : pkle){
         pkListValues.add(pklVal.getLabel());
     }     
     return pkListValues;
  }
 }  
In this controller, there are at least some information you need to take note of:   
1. The name of the controller will be included in the aura:component tag     
2. The parameters- String sObjectType, String selectedField. The two will be used in the client-side controller       
3. The method name – getPicklistValues will also be invoked by the client-side controller      
4. The attribute - @AuraEnabled must be added to the method for you to call it in the Lightning Component

This is the Service component which will populate the picklist fields with the options. Create a Service Component, call it SchoolPicklists.cmp and add the code below:

<aura:component controller="PickListApexController" access="global">
<aura:attribute name="sObjectName" type="String" />
<aura:attribute name="fieldName" type="String" />
<aura:attribute name="picklistValues" type="Object" />   
<aura:handler name="init" value="{!this}" action="{!c.doInit}" />

</aura:component>

Save it and on the right-hand side click the Controller pane. Copy and paste the code below

({
    doInit : function(component) {
        var action = component.get("c.getPickListValues");
        action.setParams({
            objectType: component.get("v.sObjectName"),
            selectedField: component.get("v.fieldName")
        });
        action.setCallback(this, function(response) {
            var pklist = response.getReturnValue();
            component.set("v.picklistValues", pklist);            
        })
        
        $A.enqueueAction(action);
    }
})

Go to File |Save All.

If everything goes well, you can view your form either on a Record Page or create a Lightning Application for it.

Reference

Lightning Aura Components Developer Guide

Trailhead

This Post Has One Comment

Leave a Reply