earnold
7/4/2018 - 3:22 PM

Contact List

Display contacts associated with an account as a lightning component

({
	myAction : function(component, event, helper) {
        // Define columns to pass to datatable
        component.set("v.Columns", [
            {label:"First Name", fieldName:"FirstName", type:"text"},
            {label:"Last Name", fieldName:"LastName", type:"text"},
            {label:"Phone", fieldName:"Phone", type:"phone"}
        ]);

        // Call getContacts from Apex controller, pass to action
		var action = component.get("c.getContacts");
        
        // Pass the recordID to action
        action.setParams({
            recordId: component.get("v.recordId")
        });
        
        // Populate the Contacts attribute with the results
        action.setCallback(this, function(data) {
            component.set("v.Contacts", data.getReturnValue());
        });
        $A.enqueueAction(action);

	}
})
 <aura:component controller="ContactListController" 
                 implements="flexipage:availableForRecordHome,force:hasRecordId" 
                 access="global" >

	<aura:attribute name="recordId" type="Id" />
    <aura:attribute name="Account" type="Account" />
    <aura:attribute name="Contacts" type="Contact" />
    <aura:attribute name="Columns" type="List" />

    <!-- On initialization of the component, get contact records -->     
    <aura:handler name="init" value="{!this}" action="{!c.myAction}" />

    <force:recordData aura:id="accountRecord"
                      recordId="{!v.recordId}"
                      targetFields="{!v.Account}"
                      layoutType="FULL"/>
     
    <lightning:card iconName="standard:contact" title="{! 'Contact List for ' + v.Account.Name}">
        <lightning:datatable data="{! v.Contacts }" columns="{! v.Columns }" keyField="Id" hideCheckboxColumn="true"/>
    </lightning:card>

</aura:component>
public class ContactListController {
    @AuraEnabled
    public static List<Contact> getContacts(Id recordId) {
       return [Select Id, FirstName, LastName, Email, Phone From Contact Where AccountId = :recordId];
    }
}