Based on picklist value in one component, display the message in another component using Events in Lightning

By | November 26, 2019

Hi, Here we have shown, Based on picklist value you have selected, selected picklist value will be displayed in the child component using events.

Here, we have shown the connection between 2 components.

Data will be modified in 2 component based on 1st component picklist value.

Apex Controller

public class BasedOnPicklistValueChangeValueinAnother {
    @AuraEnabled
    public static List < String > getselectOptions(sObject objObject, string fld) {        
        List <String> allOpts = new list <String> ();
        // Get the object type of the SObject.
        Schema.sObjectType objType = objObject.getSObjectType();
        
        // Describe the SObject using its object type.
        Schema.DescribeSObjectResult objDescribe = objType.getDescribe();
        
        // Get a map of fields for the SObject
        map <String, Schema.SObjectField> fieldMap = objDescribe.fields.getMap();
        
        // Get the list of picklist values for this field.
        list <Schema.PicklistEntry> values =
            fieldMap.get(fld).getDescribe().getPickListValues();
        
        // Add these values to the selectoption list.
        for (Schema.PicklistEntry a: values) {
            allOpts.add(a.getValue());
        }        
        allOpts.sort();
        return allOpts;
    }
}

Lightning Event : component level event

<aura:event type="COMPONENT" description="Event template" >
    <aura:attribute name="Changevalue" type="string"/>
</aura:event>

Lightning Component (Parent) : BasedOnPicklistValueChangeValueinAnotherComp

<aura:component controller="BasedOnPicklistValueChangeValueinAnother" 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="objInfo" type="account" default="{sobjectType : 'Account'}" />
    <aura:registerEvent name="sampleEvent" type="c:BasedOnPicklistValueChangeValue" />
   
    <div class="slds-form-element">
        <label class="slds-form-element__label" for="select-01">Select Label</label>
        <div class="slds-select_container">
            <ui:inputSelect  aura:id="accIndustry" class="slds-select"  change="{!c.onPicklistChange}"/>
        </div>        
    </div>
</aura:component>

Controller js

({
    doInit: function(component, event, helper) {
        helper.fetchPickListVal(component, 'Industry', 'accIndustry');
    },
    onPicklistChange: function(component, event, helper) {
        // get the value of select option
      var Codes = event.getSource().get("v.value");
        alert(Codes);
       var cmpEvent=component.getEvent("sampleEvent");
        cmpEvent.setParams({"Changevalue" : Codes});
        cmpEvent.fire();
    },
})

Helper js

({
    fetchPickListVal: function(component, fieldName, elementId) {
        var action = component.get("c.getselectOptions");
        action.setParams({
            "objObject": component.get("v.objInfo"),
            "fld": 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++) {
                    opts.push({
                        class: "optionClass",
                        label: allValues[i],
                        value: allValues[i]
                    });
                }
                component.find(elementId).set("v.options", opts);
            }
        });
        $A.enqueueAction(action);
    },
})

Lightning Compnent (Child) : BasedOnPicklistValueChangeVal

<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" >
    <aura:handler name="sampleEvent" event="BasedOnPicklistValueChangeValue" action="{!c.parent}" />
    <aura:attribute name="eventMessage" type="String" />
    <aura:attribute name="Show" type="boolean" default="false" />
    
    
    <c:BasedOnPicklistValueChangeValueinAnotherComp/>
    
    <aura:if isTrue="{!v.Show}">
        <lightning:card footer="Salesforcecodes.com" title="">
            <div class="Codes">{!v.eventMessage}</div>   
        </lightning:card>
    </aura:if>
</aura:component>

Controller js

({
    parent : function(component, event) {
        var text = event.getParam("Changevalue");
        if(text == 'Entertainment'){
            component.set("v.eventMessage", text);
            component.set("v.Show", true);
        }
        else{
            alert("Message displays for Entertainment Only");
            component.set("v.Show", false);
        }
    }
})

Styles Css

.THIS .Codes{
    background:cyan;
    font-size:22px;
    font-family:Monotype Corsiva;
    font-weight: bold;
}

Application

<aura:application Extends="force:slds">
    <c:BasedOnPicklistValueChangeVal/>
</aura:application>

Output

Here i selected the value of Entertainment from parent, then the child component which I applied styles to display the value in the second component which is selected will be displayed.
Hence the Connection between two components has been shown successfully using Events in salesforce lightning. We have applied coe only for Entertainment here.
Share this...
Share on Facebook
Facebook
Email this to someone
email

Leave a Reply

Your email address will not be published. Required fields are marked *