Sunday, 25 March 2018

Lightning Picklist Helper and Component Event Example

Hi ,

I am going to explain a reusable component for picklist . We can use it in any component for generating picklist.

It has following parameters to set dynamically.
objectName -- For which object we have to generate piclist
FieldName -- It is Picklist Field API name
FieldLabel -- Label of the Picklist field
MultiSelect -- We can setup picklist as muliselect or single select
SelectedValue -- We can set up default value

We have to create an event to pass selected value from PicklistHelper Component. Here

we are using component event.

PickListEvent.evt:

<aura:event type="Component" description="Event fire when some one selects a value in picklist" >
    <aura:attribute name="SelectedValue" type="string" description="The result of the Selection"/>

</aura:event>


PicklistHelper.cmp:

<aura:component controller="PicklstHelper">
  <aura:registerEvent name="PicklistSelected" type="c:PickListEvt"/>
   <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
   <aura:attribute name="objectName" type="String"/>
    <aura:attribute name="FieldName" type="String" />
    <aura:attribute name="FieldLabel" type="String" default="PickLIst"/>
    <aura:attribute name="MultiSelect" type="Boolean" default="false" />
    <aura:attribute name="SelectedValue" type="String" default="" />
   <div class="slds-form-element">
      <label class="slds-form-element__label" for="select-01">{!v.FieldLabel}</label>
      <div>
         <ui:inputSelect aura:id="PickListId" multiple="{!v.MultiSelect}" class="slds-select"  change="{!c.onPicklistChange}"/>
      </div>
   </div>

</aura:component>

PickListHelperController.JS:
---------------------
({
    doInit: function(component, event, helper) {        
        helper.fetchPickListVal(component, 'PickListId', component.get("v.SelectedValue"));
    },
onPicklistChange : function(component, event, helper) {
// get the value of select option
        var SelectPicklist = component.getEvent("PicklistSelected");
        SelectPicklist.setParams({
            SelectedValue: event.getSource().get("v.value")
        }).fire();      
}
})

PickListHelperHelper.JS:
---------------------
({
fetchPickListVal: function(component, elementId, selectedVal) {
        var action = component.get("c.getselectOptions");
        action.setParams({
            "objectName": component.get("v.objectName"),
            "fieldName": component.get("v.FieldName")
        });
        var opts = [];
        action.setCallback(this, function(response) {
            if (response.getState() == "SUCCESS") {
                var allValues = response.getReturnValue();
                if (allValues != undefined && allValues.length > 0) {
                    opts.push({
                        class: "optionClass",
                        label: "--- None ---",
                        value: ""
                    });
                }
                for (var i = 0; i < allValues.length; i++) {
                    if(selectedVal == allValues[i])
                    {
                        opts.push({
                            class: "optionClass",
                            label: allValues[i],
                            value: allValues[i],
                            selected: "true"
                        });
                        var SelectPicklist = component.getEvent("PicklistSelected");
                        SelectPicklist.setParams({
                            SelectedValue: selectedVal
                        }).fire(); 
                    }
                    else
                    {
                        opts.push({
                            class: "optionClass",
                            label: allValues[i],
                            value: allValues[i],                          
                        });
                }
                }
                component.find(elementId).set("v.options", opts);
            }
        });
        $A.enqueueAction(action);
    }

})

PickListHelper.CSS
---------------------------
.THIS .optionClass {
    padding: .1rem;
}
.THIS .slds-select[size] option {
    padding: .1rem;
}
.THIS .slds-select[multiple] option {
    padding: .1rem;
}


Apex Controller:
----------------------
public class PicklstHelper {
    @AuraEnabled
    public static List < String > getselectOptions(String objectName, string fieldName) {
       List<String> optionsList = new List<String>();
       list <Schema.PicklistEntry>  piclistValueList = schema.getGlobalDescribe().get(objectName).getDescribe().fields.getMap().get(fieldName).getDescribe().getPicklistValues();
        for(Schema.PicklistEntry pickEntryObj:piclistValueList){
            optionsList.add(pickEntryObj.getValue());
        }
       
        return optionsList;
    }
}

AccountSave.cmp: (Component where we are going to utilize the above picklist Helper component)

<aura:component controller="AccountSavecls">
    <aura:attribute name="accountObj" type="Account" default="{'sobjectType': 'Account',
                          'Name':'','Type':''}"/>
    <div class="slds">        
        <div class="slds-card">
            <div class="slds-card__header slds-grid">
                <div class="slds-media__body">
                    <span class="slds-text-heading_small">Save Contact and Add it to table with checkbox selection</span>
                </div>
            </div>
            <div class="slds-card__body slds-card__body_inner">
                <ui:inputText class="slds-input" label="Name"  value="{!v.accountObj.Name}"/><br/>            
                <c:PickListHelper objectName="Account" 
                                  FieldName="Type" 
                                  FieldLabel="Account Type"
                                  SelectedValue="Customer - Direct"
                                  PicklistSelected="{!c.changeValue}"/><br/>
                <ui:button class="slds-button" press="{!c.saveAct}">Save Account</ui:button>
            </div>
        </div>   
    </div>
</aura:component>

AccountSaveController.js:
({
saveAct : function(component, event, helper) {       
        var actRec = component.get("v.accountObj");
var action = component.get("c.saveAccout");
        action.setParams({"actObj":actRec});
        action.setCallback(this,function(response){
            var result = response.getReturnValue();            
        });
        $A.enqueueAction(action);
},
    changeValue : function(component,event,helper){        
        component.set("v.accountObj.Type", event.getParam("SelectedValue"));
    }
})

AccountSaveApp.App;



output:
---------



References:
https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/events_component.htm
https://trailhead.salesforce.com/modules/lex_dev_lc_basics/units/lex_dev_lc_basics_events
https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/events_intro.htm








1 comment:

  1. Really is very interesting, I saw your website and get more details..Nice work. Thanks regards, salesforce training

    ReplyDelete

What’s the difference between Einstein Article Recommendations and Suggested Articles?

How Does Einstein Article Recommendations Work? Einstein Article Recommendations helps support agents resolve customer cases efficiently by ...