function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
SV MSV M 

Display Contacts and Opportunities related to Account in Lightning

Hi, I wanted to show Accounts with checkbox on my page. If I select an account and click Next button I want to display contacts related to that Account. Can someone help me how to do this using Aura Components since I am new to Aura Components. Thanks in Advance...
Suraj Tripathi 47Suraj Tripathi 47
Hi,
Below is the code you will get a list of account record while you will select account then its related opportunity and contacts will show.

<!--      AURA Comonent   -->

<aura:component controller="AccountApex" 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="accountList" type="list"/>
    <aura:attribute name="selectedAccount" type="account"/>
    <aura:attribute name="contactList" type="list"/>
    <aura:attribute name="opportunityList" type="list"/>
   
    <lightning:select name="selectItem" label="Select Account" aura:id="ac" onchange="{!c.getDetail}" >
        <aura:iteration items="{!v.accountList}" var="acc">
            <option label="{!acc.Name}" value="{!acc.Id}" />
        </aura:iteration>
    </lightning:select>
    
    <lightning:select label="contact list" >
    <aura:iteration items="{!v.contactList}" var="con">
        <option label="{!con.LastName}" value="{!con.Id}"/>  
    </aura:iteration> 
   </lightning:select>
    
    <lightning:select    label="Opportunity list" >
    <aura:iteration items="{!v.opportunityList}" var = "op">
        <option label="{!op.Name}" value="{!op.Id}"/>    
    </aura:iteration>
     </lightning:select>
    
</aura:component>


//   CONTROLLER
({
    doInit : function(component, event, helper) {
        helper.getAllAccount(component, event, helper);
    },
    
    getDetail: function(component, event, helper){
        helper.helperGetDetail(component, event, helper);
         helper.helperGetOpportunity(component, event, helper);
    }  
})

//    HELPER

({
getAllAccount : function(component, event, helper) {
        var action=component.get('c.fetchAccount');
        action.setCallback(this,function(response){
           console.log('response===>  '+JSON.stringify(response.getReturnValue()));
            if(response.getReturnValue()!=null){
                console.log('success');
                component.set('v.accountList',response.getReturnValue());
            }
        });
        $A.enqueueAction(action);
    },   
    
        helperGetDetail: function(component, event, helper){
        var acid=component.find('ac').get('v.value');
        console.log(acid);
        var action=component.get('c.getContact');
        action.setParams({
            accid:acid
        });
         action.setCallback(this,function(response){
           console.log('response===>  '+JSON.stringify(response.getReturnValue()));
            if(response.getReturnValue()!=null){
                console.log('success');
                component.set('v.contactList',response.getReturnValue());
            }
        });
        $A.enqueueAction(action);
    },
    
    helperGetOpportunity : function(component, event, Helper){
    var opid = component.find('ac').get('v.value');
    console.log(opid);
    var action = component.get('c.getopportunity');
    
    action.setParams({
                accid:opid
});
action.setCallback(this, function(response){
    console.log('opp response==>  '+JSON.stringify(response.getReturnValue()));
    if(response.getReturnValue() != null){
        console.log("OPP success");
        component.set('v.opportunityList', response.getReturnValue());
        console.log("Pass");
    }
}); 
  $A.enqueueAction(action);
}
})


// APEX
public class AccountApex {
    @auraEnabled
    public static list<account> fetchAccount(){
        list<account> accList= new list<account>();
        accList=[select name from account];
        return accList;
    }
    
      @auraEnabled
    public static list<contact> getContact(id accid){
        list<contact> conList= new list<contact>();
        conList=[select lastname from contact where accountid =:accid];
        return conList;
    }
    
    @auraEnabled
    public static list<opportunity> getopportunity(id accid){
        list<opportunity> opList = new list<opportunity>();
        opList = [select name from opportunity where accountid =: accid];
        return opList;
    }
}



Please mark it as Best Answer if it helps you.

Thanks & Regards
Suraj Tripathi

 
CharuDuttCharuDutt
Hii Sai Vineeth Maddula
​​​​​​Try Below Code
<aura:component implements="force:appHostable"
   controller="AccountListController">
   <aura:attribute type="Account[]" name="acctList"/>
   <aura:attribute type="Contact[]" name="conList"/>
     <aura:attribute name="SelectedAccount" type="String"/>
   <aura:attribute name="searchKeyword" type="String" />
   <aura:handler name="init" value="{!this}" action="{!c.init}"/>
   <div class="slds-box slds-theme_default">
     <table class="slds-table slds-table_bordered slds-table_cell-buffer">
<thead>
   <tr class="slds-text-title_caps">
      <th scope="col"></th>
      <th scope="col">Persona</th>
   </tr>
</thead>
<tbody>
   <aura:iteration items="{!v.acctList}"  var="acc">
      <tr scope="row">
         <td>    <input type="checkbox" name="chk" id="{!acc.Id}" onchange="{!c.getSelectedAccount}"/></td>
         <td>{!acc.Name}</td>
      </tr>
   </aura:iteration>
</tbody>
</table>
<table class="slds-table slds-table_bordered slds-table_cell-buffer">
<thead>
   <tr class="slds-text-title_caps">
      <th scope="col">Contact</th>
   </tr>
</thead>
<tbody>
   <aura:iteration items="{!v.conList}"  var="con">
      <tr scope="row">
         <td>{!con.Name}</td>
      </tr>
   </aura:iteration>
</tbody>
</table>
        </div>
</aura:component>


Controller:
({
    getSelectedAccount : function(component, event,helper) { 
        var selectedId='';          
        selectedId = event.target.getAttribute('id');
        alert(selectedId);
        component.set('v.searchKeyword', selectedId);
             var action = component.get('c.fetchCons');
         action.setParams({ Accid : component.get("v.searchKeyword"),
                         });
        action.setCallback(this, function(response){
            var state = response.getState();
            if(state === "SUCCESS"){
                var allValues = response.getReturnValue();
                console.log("allValues--->>> " + JSON.stringify(allValues));
                //component.set('v.activeSections', allValues.Name);
                component.set('v.conList', allValues);
            }
            else if(state === "ERROR") {
                var errors = response.getError();
                if(errors){
                    if(errors[0] && errors[0].message){
                        console.log("Error Message: " + errors[0].message);
                    }
                }
                else{
                    console.log("Unknown Error");
                }
            }
        });
        $A.enqueueAction(action);
    }

})

Helper
({
    
 fetchAccounts : function(component, event) {
  
        var action = component.get("c.fetchAccts");
        
        action.setCallback(this, function(response) {
            
            var state = response.getState();
            
            if (state === "SUCCESS") {
                
                var records = response.getReturnValue();
                records.forEach(function(record) {
                    
                    record.linkName = '/' + record.Id;
                    record.CheckBool = false;
                    
                });   
                
                component.set("v.acctList", records);
                
            }            
            
        });
        
        $A.enqueueAction(action);
        
 }
    
})

Apex
public class AccountListController {
    
    @AuraEnabled
    public static List < Account > fetchAccts() {
        
        return [ SELECT Id, Name FROM Account ];
        
    }
    @AuraEnabled
    public static List < Contact > fetchCons(id Accid) {
        
        return [ SELECT Id,Name,AccountId FROM Contact Where AccountId = :Accid];
        
    }
    
}
Please Mark It As Best Answer If It Helps
Thank You!




 
SV MSV M
Thanks Suraj & ChruDutt for your response. I understood the component well. I would like to show a checkbox for each account and if I select any account and click on a Button then I want to show related childs. Can you help me how to develop this requirement.