Saturday, April 18, 2020

Create and Use Map in a Lightning Component




Our Org has email addresses of Contacts Users in the format of FirstName.LastName@companyDomain.

We have a requirement to show the FirstName.LastName of the users on a lightning Component as a table.

Apex Class (testClass.apxc):

@AuraEnabled
    public static List<User> getUsers(){
        return [SELECT Id, Name, Email FROM User LIMIT 10];
    }

Lightning Component (testCMP):
.cmp

<aura:component controller="testClass" implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,force:lightningQuickAction" access="global" >

<aura:attribute name="myMap" type="Map"/>
    <aura:handler name="init" value="{!this}" action="{!c.doInit}" />
    <lightning:card>
<table class="slds-table slds-table_cell-buffer slds-table_bordered slds-max-medium-table_stacked-horizontal">
<thead>
<tr class="slds-line-height_reset">
<th class="" scope="col">
<div class="slds-truncate" title="ID">ID</div>
</th>
      <th class="" scope="col">
<div class="slds-truncate" title="Email">Email</div>
</th>
<th class="" scope="col">
<div class="slds-truncate" title="Username">FirstName.LastName</div>
</th>
</tr>
</thead>
<tbody>
<aura:iteration items="{!v.myMap}" var="mapvar" indexVar="key">
<tr data-target-id = 'eachRow' class="slds-hint-parent">
                            <td data-label="Id">
<div class="slds-truncate" title="Id">{!mapvar.key.Id}</div>
</td>
<td data-label="Email">
<div class="slds-truncate" title="Email">{!mapvar.key.Email}</div>
</td>
<td data-label="Username">
<div class="slds-truncate" title="FirstName.LastName">{!mapvar.value}</div>
</td>
</tr>
     </aura:iteration>
</tbody>
</table>
    </lightning:card>
</aura:component>

.controller.js

({
doInit : function(component, event, helper) {
var action = component.get("c.getUsers");
                action.setCallback(this, function(response){
                if(response.getState() == "SUCCESS"){
                    var result= response.getReturnValue();
                    var lst = [];
                    for(var i=0; i<result.length; i++){
                        let username = result[i].Email.split('@')[0];
                        lst.push({value:username, key:result[i]});
                    }
                   component.set("v.myMap", lst);
               }
           });
         $A.enqueueAction(action);
}
})