Collections In Lightning Components


Collections are building blocks for any object oriented programming language. In Apex we use LIST, SET, MAP collection types in order to work with records!

Here in this blog, we are going look at some basic code on using Collection Types in context with Lightning Components.....


First we create an Apex Controller with two methods to return List and Map respectively. We will use these methods to access from our Lighting Component and display them on the Home Page.

public class LightningCollectionTypes {
    @AuraEnabled
    public static List<Account> lghtList() {
        List<Account> lstAccnts = [SELECT Id, Name FROM Account LIMIT 22];
        return lstAccnts;
    }

    @AuraEnabled
    public static Map<Id, Account> lghtMap() {
        Map<ID, Account> m = new Map<ID, Account>([SELECT Id, Name FROM Account LIMIT 22]);
        return m;
    }
}

LIST

  • Below are component and controller code for 'ListComp' lightning component that will get data from Apex controller method to store in a List and display it on the UI.
  • ListComp.cmp

    <aura:component controller="LightningCollectionTypes" implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,force:lightningQuickAction" access="global" >
        <!--List component attribute-->
        <aura:attribute name="accntsList" type="Account[]"/>
        
        <center>
            <!--Button which calls controller action to get List values-->
            <lightning:button onclick="{!c.getListAccounts}" label="List Accounts"/>
        </center>
        
        <!--Construct HTML Table using SLDS-->
        <table class="slds-table slds-table--bordered slds-table--striped slds-table--cell-buffer slds-table--fixed-layout">
            <thead>
                <tr class="slds-text-heading--label">
                    <th scope="col"><div class="slds-truncate" title="ID">ID</div></th>
                    <th scope="col"><div class="slds-truncate" title="Name">Name</div></th>
                </tr>
            </thead>
            <tbody>
                <!--Iterate through List results-->
                <aura:iteration items="{!v.accntsList}" var="a">
                    <tr>
                        <td><div class="slds-truncate" title="{!a.Name}">{!a.Id}</div></td>
                        <td><div class="slds-truncate" title="{!a.Type}">{!a.Name}</div></td>
                    </tr>
                </aura:iteration>
            </tbody>
        </table>    
    </aura:component>
    

    ListComp.js

    /** Client-side Controller **/
    ({
        getListAccounts: function(cmp, event, helper) {
            // Get list data by calling apex controller method
            var action = cmp.get("c.lghtList");
            action.setCallback(this, function(response) {
                // Get callback response
                var state = response.getState();
                // On success response, assign List values to the List component attribute 
                if (state == "SUCCESS") {
                    // Log response values
                    console.log('************ReturnValues: ' + response.getReturnValue());
                    // Assign return values to the List attribute
                    cmp.set("v.accntsList", response.getReturnValue());
                }
            });
            $A.enqueueAction(action);
        }
    })
    

  • Once I have my "ListComp" lightning component created using above code and place it on the my home page, I should be able to view Accounts as below
  • SET

  • Below are component and controller code for 'SetComp' lightning component. Here were are going to form our Set data in .js controller and display it on the UI.
  • Note** @AuraEnabled methods do not support return type of 'SET' and that is the reason why I am forming my Set data in .js controller!


    SetComp.cmp

    <aura:component implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,force:lightningQuickAction" access="global" >
        <!--Set component attribute-->
        <aura:attribute name="valSet" type="Set"/>
        
        <center>
            <!--Button to display Set values-->
            <lightning:button onclick="{!c.getSetValues}" label="Set Values"/>
        </center>
        
        <!--Construct HTML Table using SLDS-->
        <table class="slds-table slds-table--bordered slds-table--striped slds-table--cell-buffer slds-table--fixed-layout">
        <thead>
          <tr class="slds-text-heading--label">
            <th scope="col"><div class="slds-truncate" title="ID">SET DATA</div></th>
          </tr>
        </thead>
        <tbody>
          <aura:iteration items="{!v.valSet}" var="s">
            <tr>
              <td><div class="slds-truncate" title="{!s}">{!s}</div></td>
            </tr>
          </aura:iteration>
        </tbody>
      </table>
    </aura:component>
    

    SetComp.js

    /** Client-side Controller **/
    ({
        getSetValues: function(cmp) {
            // Variable to input Set values manually
            var tempSet = ['SetValue1', 'SetValue2', 'SetValue3', 'SetValue4', 'SetValue5', 'SetValue6'];
            // Assign above variable to the Set attribute
            cmp.set("v.valSet", tempSet);        
        }
    })
    

  • Once I have my "SetComp" lightning component created using above code and place it on the my home page, I should be able to view Set data as below
  • MAP

  • Below are component and controller code for 'MapComp' lightning component.
  • MapComp.cmp

    <aura:component controller="LightningCollectionTypes" implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,force:lightningQuickAction" access="global" >
        <!--Map component attribute-->
        <aura:attribute name="accntsMap" type="Map"/>
        
        <center>
            <!--Button which calls controller action to get Map values-->
            <lightning:button onclick="{!c.getMapAccounts}" label="Map Accounts"/>
        </center>
        
        <!--Construct HTML Table using SLDS-->
        <table class="slds-table slds-table--bordered slds-table--striped slds-table--cell-buffer slds-table--fixed-layout">
            <thead>
                <tr class="slds-text-heading--label">
                    <th scope="col"><div class="slds-truncate" title="ID">Map Data</div></th>
                </tr>
            </thead>
            <tbody>
                <!--Iterate through List results-->
                <aura:iteration items="{!v.accntsMap}" var="a" indexVar="key">
                    <tr>
                    <td><div class="slds-truncate" title="Data">{!a.key}</div></td><br/><br/>
                        </tr>
                </aura:iteration>            
            </tbody>
        </table>
    </aura:component>
    

    MapComp.js

    /** Client-side Controller **/
    ({
        getMapAccounts: function(cmp, event, helper) {        
            // Get list data by calling apex controller method
            var action = cmp.get("c.lghtMap");
            action.setCallback(this, function(response) {
                // Get callback response
                var state = response.getState();
                // On success response, assign Map values to the List component attribute
                if (state == "SUCCESS") {
                    var cMap1 = [];
                    var cMap2 = response.getReturnValue();
                    alert(JSON.stringify(response.getReturnValue()));
                    for(var key in cMap2) {
                        cMap1.push({value:cMap1[key], key:key});
                    }
                    cmp.set("v.accntsMap", cMap1);
                    console.log('************' + cmp.get("v.accntsMap"));
                    alert('************' + cmp.get("v.accntsMap"));
                }
            });
            $A.enqueueAction(action);        
        }
    })
    

  • Once I have my "MapComp" lightning component created using above code and place it on the my home page, Below should the result view.
  • Thank you!

    Comments

    Popular posts from this blog

    Displaying Toast Message from Modal in Lightning Components

    Lightning Component to display dynamic sObject data

    Lightning RecordForm - An enhanced Lightning Data Service