+ Start a Discussion
prasanth sfdcprasanth sfdc 

Display Accounts with Contacts in lightning component.

Hi, 

I want to display list of accounts with contacts in lightning page. Here the code i have written. Here accounts are displaying but contacts are not display. Please help me to display the accounts with contacts.

Thank you.


 
<aura:component controller="accountsWithContactsClass" implements="flexipage:availableForAllPageTypes" access="global">
	 
    <aura:attribute name="accounts" type="Account[]" />
    <ui:button label="click this" press="{!c.myAction}" />
    <table>
            <tr><td><b>Name</b></td><td><b>Industry</b></td></tr>

    <aura:iteration items="{!v.accounts}" var="accs1" >
        <tr>   
        <td> {!accs1.Name}  </td>
         
      <td>   {!accs1.Industry}  </td> 
      <!--   <td>   {!accs1.Contacts.lastName}  </td> -->
        </tr>     
     <tr>   <aura:iteration items="{!v.accs1.contacts}" var="con1" >
            
             <td>{!con1.lastName} </td>
            
        </aura:iteration></tr>
     </aura:iteration>                                            
        </table>
    
</aura:component>








({
	myAction : function(component, event, helper) {
		var action =component.get("c.getAllAccounts");
        console.log('The action value is: '+action);
         action.setCallback(this, function(a){ 
             
            component.set("v.accounts", a.getReturnValue());
           //  console.log('The accs are :'+JSON.stringify(a.getReturnValue()));
            console.log('The accs are :'+JSON.stringify(a.getReturnValue()));
          
        });
        $A.enqueueAction(action);
	}
})











public class accountsWithContactsClass {

@auraEnabled
public static list<account> getAllAccounts()
    {
       list<account> accs =[select id,name,phone,industry,(select lastName from contacts) from account limit 10];
      //  list<account> accs =[select id,name,phone,industry from account limit 10];
     //   return [select Id,Name from account limit 10];
     return accs;
    }
}

 
Best Answer chosen by prasanth sfdc
Aakanksha SinghAakanksha Singh
Hi,
Try this code for your component:
<pre><aura:component controller="accountsWithContactsClass" implements="flexipage:availableForAllPageTypes" access="global">
    <aura:handler name="init" value="{!this}" action="{!c.myAction}"/>
    <aura:attribute name="accounts" type="Account[]" />
    <table>
        <tr>
            <td>
                <b>Name</b>
            </td>
            <td>
                <b>Industry</b>
            </td>
            <td>
                <b>Contacts</b>
            </td>
        </tr>
        <aura:iteration items="{!v.accounts}" var="accs1" >
            <tr>  
                <td> {!accs1.Name}  </td>
                  <td> {!accs1.Industry}  </td>
                 <!--   <td>   {!accs1.Contacts.lastName}  </td> -->
                <table>
                    <aura:iteration items="{!accs1.Contacts}" var="con1" >
                        <tr>
                            <td>{!con1.LastName}</td>
                        </tr>
                    </aura:iteration>
                </table>
            </tr> 
         </aura:iteration>                                           
    </table>    
</aura:component></pre>

If it helps, mark it as best answer.

Regards,
Aakanksha Singh

All Answers

Aakanksha SinghAakanksha Singh
Hello,
Try removing v for aura iteration for contacts.
<aura:iteration items="{!accs1.contacts}" var="con1" > 
Regards
Aakanksha
 
prasanth sfdcprasanth sfdc
not coming Aakansha singh. 
Aakanksha SinghAakanksha Singh
Hi again,
I was facing the similar situation for some other objtect, the key point to remember is Lightning component is case sensitive. I debuged your code myself, there is a minor change
<pre>
<aura:iteration items="{!accs1.Contacts}" var="con1" > 
</pre>
and
<td>{!con1.LastName}</td>
Try it, you will definitely get result. :)

Mark it as best answer, if your problem is solved.

Regards
Aakanksha Singh
 
Aakanksha SinghAakanksha Singh
*object
prasanth sfdcprasanth sfdc
Hi Thank you very much Akansha, But it is displaying only one contact for each account. In my org some accounts have more than 1 contact. Could you tell me how to fix this. Thanks in advance.

User-added image
Aakanksha SinghAakanksha Singh
Hi,
Try this code for your component:
<pre><aura:component controller="accountsWithContactsClass" implements="flexipage:availableForAllPageTypes" access="global">
    <aura:handler name="init" value="{!this}" action="{!c.myAction}"/>
    <aura:attribute name="accounts" type="Account[]" />
    <table>
        <tr>
            <td>
                <b>Name</b>
            </td>
            <td>
                <b>Industry</b>
            </td>
            <td>
                <b>Contacts</b>
            </td>
        </tr>
        <aura:iteration items="{!v.accounts}" var="accs1" >
            <tr>  
                <td> {!accs1.Name}  </td>
                  <td> {!accs1.Industry}  </td>
                 <!--   <td>   {!accs1.Contacts.lastName}  </td> -->
                <table>
                    <aura:iteration items="{!accs1.Contacts}" var="con1" >
                        <tr>
                            <td>{!con1.LastName}</td>
                        </tr>
                    </aura:iteration>
                </table>
            </tr> 
         </aura:iteration>                                           
    </table>    
</aura:component></pre>

If it helps, mark it as best answer.

Regards,
Aakanksha Singh
This was selected as the best answer
prasanth sfdcprasanth sfdc
It is displaying like Name Industry Contacts.

But i need   
Name  Industry
    Contacts 1.
    Contacts 2.
    Contacts 3.

Thank you. 
prasanth sfdcprasanth sfdc
Ok i got it. I modified the code.    Thank you very much akansha........ 
Aakanksha SinghAakanksha Singh
Ok. You're welcome.
It'sSaurabhIt'sSaurabh
hi guyz if i want to enable clicking on that account record suppose (genepoint) in our case, how can we achieve it ? i want to pass account id of genepoint and onclicking its name it should redirect me to genepoint account detail page, thanks in advance !
Aakanksha Singh 11Aakanksha Singh 11
Hello Saurabh,

You can use the below code, but it will not work in myapp.app.
<td data-label="Account Name" class="action">
    <a href="{! '#/sObject/' + acc.Id + '/view'}">{!acc.Name}</a>
</td>
Hope it helps.

Regards
Aakanksha Singh
 
Sunil pal 29Sunil pal 29
Hi All,

Thank you for sharing the code. Please let me know if any one have this with inline edit also with all fields in lightning.
Arun Garg 9Arun Garg 9
Refer this link to display Accounts record using lightning components.
Display Accounts Record Using Lightning Component (http://www.salesforceadda.com/2017/08/display-accounts-record-using-lightning.html)
Naveen PoojaryNaveen Poojary
My parent component
<aura:component controller="RetrieveAccout" access="global"  implements="flexipage:availableForAllPageTypes">
    <aura:attribute name="Accc" type="Account[]"/> 
    <aura:attribute name="Conts" type="Contact[]"/> 
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
    <table class="slds-table slds-table_bordered slds-table_cell-buffer">
        <thead><tr class="slds-text-title_caps">
            <th></th></tr>
            <tr class="slds-text-title_caps">
                <th scope="col" class="">
                    <div class="slds-truncate" title="Name">Account Name</div>
                </th>
                <th scope="col" class="">
                    <div class="slds-truncate" title="Id">ID</div>
                </th>
                <th scope="col" class="">
                    <div class="slds-truncate" title="Phone">Phone</div>
                </th>
                <th scope="col" class="">
                    <div class="slds-truncate" title="Email">Type</div>
                </th>  
            </tr>
        </thead>  
        <tbody>
            <aura:iteration items="{!v.Accc}" var="Act"  indexVar="acti">
           <tr>
                    <td scope="row" data-label=" Name" class="">
                        <div class="slds-truncate" >{!Act.Name}</div> 
                    </td>
                
               
                    <td data-label="ID">
                        <div class="slds-truncate" >{!Act.Id}</div>
                    </td>
                    <td data-label="Phone">
                        <div class="slds-truncate" >{!Act.Phone}</div>
                    </td>
                    <td data-label="Type">
                        <div class="slds-truncate" >{!Act.Type}</div>
                    </td> 
                    <td data-label="Type">
                       <div class="slds-truncate" >
                            <aura:iteration items="{!Act.Contacts}" var="cont" >
                                <c:Assignment27child Cnts="{!v.Accc}"/><br/>
                            </aura:iteration>                                                        
                        </div>
                    </td>
                    
                </tr>
            </aura:iteration>
            </tbody>
    </table>  
    <!-- <c:Assignment27child Cnts="{!Accc}"/><br/>-->    
</aura:component>

RetrieveAccout.apxc
public class RetrieveAccout 
{
@AuraEnabled
    public static List<Account> getAccountDataAssignment27()
    {
        List<Account>Act=([select Name,Id,Phone,Type,(Select FirstName,LastName,Email,Phone from Contacts) from Account Order By createddate Desc Limit 10]);
        return Act;
    }
}

Hi all
I have an parent component which displays 10 accounts in my org in a table format with the ids. I made an hyperlink to my account name when i click on that account related contact records a need to be displayed in my child component. i want to send the account id to controller individually through aura iteration  how can i send this id to my controller.js  remaiining i will do.
Aakanksha Singh 11Aakanksha Singh 11
Hello Naveen,
Please refer to the blog link mentioned below: 
https://wedgecommerce.com/massdelete-lightning-component/
I think you might get your answer
Regards
Aakanksha Singh
Naveen PoojaryNaveen Poojary
Thank you Aakanksha 
As per your responce link it will pass the id to controller from inputCheckbox i want to pass the id on achor tag like the sample code
When i clicked on the Account name i want to pass the value of that rows account id  to controller passid. how can i do that please help out i dont want pass array of account ids to controller.
Regards 
Naveen Poojary 
<table>
<aura:iteration items="{!v.Acontlist}" var="Act">
 <tr> 
    <td "> 
       <div> 
           <a onclick="{!c.passid}" value="{!Act.Id}">{!Act.name}</a>
      </div> 
    </td> 
  </tr> 
</table>

 
Aakanksha Singh 11Aakanksha Singh 11
Hello Naveen,
You can try this:
({
    passid:function(component,event,helper){
        var id = event.getSource().get('v.value');
        alert(id);
    },
})
You can refer to these links as well, it might help:

https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/lightning_base_events.htm
https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/js_cb_which_button_pressed.htm

Regards
Aakanksha Singh
Naveen PoojaryNaveen Poojary
It worked for me Thank you Aakanksha.
Regards 
Naveen Poojary
Gopi SalesforceGopi Salesforce
Hi Naveen,

Please post your total code..

i have same requirement to display contacts when click on account name
 
Megha NairMegha Nair
Can you please help me out to display the contacts related to the selected account names from picklist.
Megha NairMegha Nair
Account names in picklist.
Related Contacts should display in Table format
Naveen PoojaryNaveen Poojary
Hi Gopi,
Sorry for the delayed reply
This is the code i used for the requirement .
<aura:component controller="RetrieveAccout" access="global"  implements="flexipage:availableForAllPageTypes">
    <aura:attribute name="Accc" type="account[]"/> 
    <aura:attribute name="Conts" type="contact[]"/> 
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
    <table class="slds-table slds-table_bordered slds-table_cell-buffer">
        <thead>
            <tr class="slds-text-title_caps">
                <th scope="col" class=""><div class="slds-truncate" title="Name">Account ID</div></th>
                <th scope="col" class=""><div class="slds-truncate" title="Id">Account Name</div></th>
                <th scope="col" class=""><div class="slds-truncate" title="Phone">Phone Number</div></th>
                <th scope="col" class=""><div class="slds-truncate" title="Email">Account Type</div></th>  
            </tr>
        </thead>  
        <tbody>
            <aura:iteration items="{!v.Accc}" var="Act">
                <tr>
                    <td scope="row" data-label=" Name" class="">
                        <div class="slds-truncate" ><ui:outputText value="{!Act.Id}" click="{!c.ShowContacts}"/></div></td>              
                    <td data-label="ID">   <div class="slds-truncate" >{!Act.Name}</div></td>
                    <td data-label="Phone"><div class="slds-truncate" >{!Act.Phone}</div></td>
                    <td data-label="Type"> <div class="slds-truncate" >{!Act.Type}</div></td> 
                </tr>
            </aura:iteration>
        </tbody>
    </table> 
    <c:childcomponent Cnts="{!v.Conts}"/><br/>      
</aura:component>

Controller:
({
    doInit : function(component, event, helper)
    {
        helper.getActs(component);
    },    
    ShowContacts : function(component, event, helper)
    {
        var actId = event.getSource().get("v.value");
        var action = component.get("c.getListofContacts");
        action.setParams({"AcctId":actId});
        action.setCallback(this,function(result)
                           {
                               var state = result.getState();
                               if (state =="SUCCESS")
                               {
                                   var v=result.getReturnValue();
                                   if(v == null || v == '')
                                   {
                                       alert("No contact Record Exists for this Account");
                                       component.set("v.Conts",'');
                                   }
                                   else
                                   {                                     
                                       component.set("v.Conts",result.getReturnValue());
                                                                           
                               		}
                               }
                           });
        $A.enqueueAction(action);
    }
})
Helper:
({
    getActs : function(component) 
    {
        var action = component.get('c.getAccountData');    
            action.setCallback(this, function(actionResult) 
                           {
                               var Results=actionResult.getReturnValue();
                               component.set("v.Accc",Results);
                               
                           });
        $A.enqueueAction(action);
        
    }   
})


Apex:
public class RetrieveAccout 
{
    @AuraEnabled
    public static List<Account> getAccountData()
    {
        List<Account>Act=([select Name,Id,Phone,Type from Account Order By createddate Desc Limit 10]);
        return Act;
    }
    @AuraEnabled
    public static List<contact> getListofContacts(String AcctId)
    {
        List<contact> cnts=([Select FirstName,LastName,Email,Phone from Contact where AccountId=:AcctId]);    
        return cnts;
    }
}

Child Component:
<aura:component controller="RetrieveAccout" access="global"  
                implements="flexipage:availableForAllPageTypes">
    <aura:attribute name="Cnts" type="contact[]"/>  
    
    <table class="slds-table slds-table_bordered slds-table_cell-buffer">
        <thead><tr class="slds-text-title_caps">
            <th></th></tr>
            <tr class="slds-text-title_caps">
                <th scope="col" class="">
                    <div class="slds-truncate" title="Name">Contact First Name</div>
                </th>
                <th scope="col" class="">
                    <div class="slds-truncate" title="Id">Contact LastName</div>
                </th>
                <th scope="col" class="">
                    <div class="slds-truncate" title="Phone">Phone</div>
                </th>
                <th scope="col" class="">
                    <div class="slds-truncate" title="Email">Email</div>
                </th>  
            </tr>
        </thead>  
        <tbody>
            <aura:iteration items="{!v.Cnts}" var="cnt">
                <tr>   
                    <td scope="row" data-label=" FirstName" class="">
                        <div class="slds-truncate" >{!cnt.FirstName}</div>
                    </td>
                    <td data-label="LastName">
                        <div class="slds-truncate" >{!cnt.LastName}</div>
                    </td>
                    <td data-label="Phone">
                        <div class="slds-truncate" >{!cnt.Phone}</div>
                    </td>
                    <td data-label="Email">
                        <div class="slds-truncate" >{!cnt.Email}</div>
                    </td>  
                </tr>
            </aura:iteration>
        </tbody>
    </table>   
</aura:component>

 
Megha NairMegha Nair
Hi Naveen ,
Thank you. This code is working fine
 
Megha NairMegha Nair
Even the below code is working fine .

Application :

<aura:application extends="force:slds" controller="accountsWthContactClass">
    <aura:attribute name="accounts" type="Account[]" />
    <aura:handler name="init" value="{!this}" action="{!c.doInit}" />
    
     <lightning:select label="Accounts" name="Op" aura:id="Op" onchange="{!c.handleAccountChange}" >
        <aura:iteration items="{!v.accounts}" var="account">
            <option value="{!account.Id}">{!account.Name}</option>
        </aura:iteration>
    </lightning:select>
     <aura:attribute name="contacts" type="contact[]"/>
    <aura:attribute name="isOpen" type="boolean" default="false"/>
 
         <div class="slds-m-around--xx-large">
            <div class="slds-modal__header">
                Related Contacts        
               </div>

                             <div class="slds-modal__content slds-p-around_medium" >
                                <table class="slds-table slds-table_bordered slds-table_cell-buffer"    >
                                    <tr class="slds-text-title_caps">
                                        <td>FirstName</td>
                                        <td>Email</td>
                                        <td>Phone</td>
                                        <td>CreatedDate</td>
                                    </tr>
                                 <aura:iteration items="{!v.contacts}" var="cons" >
                                   <tr>
                                    <td> {!cons.FirstName} </td>
                                    <td> {!cons.Email} </td>
                                    <td> {!cons.Phone} </td>
                                    <td> {!cons.CreatedDate}</td></tr>
                                  </aura:iteration>

                                </table>
                             </div>

                              

         </div>
    </aura:application>

Controller:
({
    
     doInit: function(component, event, helper) {
       
        var action = component.get("c.getAllAccounts");
        action.setCallback(this, function(result){
            var accounts = result.getReturnValue();
            console.log(accounts);
            component.set("v.accounts",accounts);
            
            window.setTimeout(
                $A.getCallback( function() {
                   
                    component.find("Op").set("v.value", accounts[4].Id);
                }));
        });
        $A.enqueueAction(action);
    },
    
   handleAccountChange : function(component, event, helper) {
        
        var accId = event.getSource().get("v.value");
        var action = component.get("c.getAllContacts");

        action.setParams({
           "ParentId": accId
        });
        action.setCallback(this, function(response){
        var state = response.getState();
            if (component.isValid() && state === "SUCCESS"){
               
                component.set("v.contacts", response.getReturnValue());
             }
            else {
                console.log("Failed with state" + state);
            }
           
        })
        $A.enqueueAction(action);
         component.set("v.isOpen", true);  
        },
     Close: function(component, event, helper) {
       
                                       
        component.set("v.isOpen", false);
   },
 });


 
Megha NairMegha Nair
User-added image
RajnRajn
Plz any one tell  how  to show above requiremnet in Grid view 
Naveen PoojaryNaveen Poojary
Hi Rajn please refer the SLDS grid It will help you
https://www.lightningdesignsystem.com/utilities/grid/
Raviteja P 31Raviteja P 31
hiii naveen poojari,
Without using "Static " keyword in method,How to display all contacts in lightning page
Thanks
Raviteja P
Salesforce CodesSalesforce Codes
this is perfect code to your scenario
Display Related contacts when we click on Account record using Lightning component
User-added image

http://salesforcecodes.com/display-related-contacts-when-we-click-on-account-record-using-lightning-component/ (http://salesforcecodes.com/display-related-contacts-when-we-click-on-account-record-using-lightning-component/" target="_blank)