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
Radha 24Radha 24 

how to show contacts of Account using LWC

l want to disply related contacts of currect account record using LWC.
Thank you!

 
AbhinavAbhinav (Salesforce Developers) 
Hi Radha,

Please go through below link it has implementation similar to your use case.

https://www.w3web.net/display-account-related-contacts-in-lwc/

https://pritamshekhawat.wordpress.com/category/lightning-component/lightning-web-component/

If it helps please mark it as best answer.

Thanks!
ANUTEJANUTEJ (Salesforce Developers) 
Hi Radha,

>> https://salesforce.stackexchange.com/questions/298048/need-help-with-lwc-trying-to-create-datatable-to-show-related-contacts-with

The above link has an implementation of showing related contacts can you try checking it once?

Let me know if it helps you and close your query by marking it as the best answer so that it can help others in the future.  

Thanks.
Suraj Tripathi 47Suraj Tripathi 47
Hi Radha,
You can take reference from below code.
In this code I have displayed Accountand Account related Contact and Opportunity.
---apex class
public class AccountRelatedObj {
    @auraEnabled(cacheable=true)
    public static List<Account> fetchAccount()
    {
        List<Account> accList=[SELECT Id,Name FROM Account LIMIT 10000];
        return accList;
    }
    @auraEnabled
    public static List<Contact> getContacts(String accountId)
    {
        List<Contact> conList=[SELECT Id,LastName,AccountId FROM Contact WHERE AccountId=:accountId LIMIT 10000];
        return conList;
    }
    @auraEnabled
    public static List<Opportunity> fetchOpportunity(String accountId)
    {
        List<Opportunity> oppList=[SELECT Id,Name,AccountId FROM Opportunity WHERE AccountId=:accountId LIMIT 10000];
        return oppList;
    }  
}
------html
<template>
    <lightning-card title="Choose Account Name" icon-name="standard:account">
    
    <table>
    <tr>
    <td>
    
    <div class="slds-m-around_medium">
    <select class="slds-select" onchange={contactFetch}>
    <option>Select Account</option>
    <template for:each ={acc} for:item="item">
    <option key={item.Id} value={item.Id}>{item.Name}</option>
    </template>
    </select>
    </div>
    </td>
    </tr>
    <tr>
    <td>
    <div class="slds-m-around_medium">
    <select class="slds-select" >
    <option >Select Contact</option>
    <template for:each ={con} for:item="item">
    <option key={item.Id} value={item.LastName}>{item.LastName}</option>
    </template>
    </select>
    </div>
    </td>
    </tr>
    
    <tr>
    <td>
    <div class="slds-m-around_medium">
    <select class="slds-select" >
    <option >Select Opportunity</option>
    <template for:each ={opp} for:item="item">
    <option key={item.Id} value={item.Name}>{item.Name}</option>
    </template>
    </select>
    </div>
    </td>
    </tr>
    </table>
    </lightning-card>
    </template>
-------.js
import { LightningElement, track, wire} from 'lwc';
import fetchAccount from '@salesforce/apex/AccountRelatedObj.fetchAccount';
import fetchContact from '@salesforce/apex/AccountRelatedObj.getContacts';
import fetchOpportunity from '@salesforce/apex/AccountRelatedObj.fetchOpportunity';

const columns = [{
    label: 'First Name',
    fieldName: 'FirstName'
},
{
    label: 'Last Name',
    fieldName: 'LastName'
},
{
    label: 'Email',
    fieldName: 'Email',
    type: 'email'
},
{
    label: 'Phone',
    fieldName: 'phone',
    type: 'phone'
}

];

const columnsOpp = [{
    label: 'Name',
    fieldName: 'Name'

}

];
 

export default class Display_Accounts_And_Related extends LightningElement {
   
@track acc;
@track con;
message;
msg;
@track opp;
connectedCallback(){
fetchAccount()
.then(result => {
this.acc = result;

console.log(JSON.stringify(result));
console.log("result",this.acc);
})

}


contactFetch(event){
this.message = event.target.value;
console.log('Contact Id-->'+this.message);
fetchContact({accountId : this.message})

.then(result => {
this.con = result;

console.log(JSON.stringify(result));
console.log("result1",this.con);
})
.catch(error =>{
this.error = error;

})

this.msg = event.target.value;
console.log('Oppoertunity Id-->'+this.msg);
fetchOpportunity({accountId : this.msg})
.then(result => {
this.opp = result;

console.log(JSON.stringify(result));
console.log("result2",this.opp);
})
.catch(error =>{
this.error = error;

})
}
}
If you find your Solution then mark this as the best answer. 

Thank you!

Regards 
Suraj Tripathi
CharuDuttCharuDutt
Hii Radha
Try Below Code
<template>
    <lightning-card title='Tab In Accordian' icon-name="custom:custom11">
        <table class="slds-table slds-table_cell-buffer slds-table_bordered">
            <thead>
                <tr class="slds-line-height_reset">
                  <th class="" scope="col">
                    <div class="slds-truncate" title="Account Name">Account Name</div>
                  </th>
                  <th class="" scope="col">
                    <div class="slds-truncate" title="Parent Account">Contacts</div>
                  </th>
                 
                </tr>
              </thead>
              <tbody>
                <template for:each={data1} for:item="acc"> 
                <tr class="" key = {acc.Id}>
                        <td data-label="Account Name">
                            <div class="slds-cell-wrap"><a href="javascript:void(0);">{acc.Name}</a></div>
                        </td>
                        <td data-label="Contacts">
                            <template for:each={acc.Contacts} for:item="con">
                                <div key={con.Id}>   
                            {con.Name}
                        </div>
                        </template>
                        </td>
                </tr>
                </template>
            </tbody>
        </table>
    </lightning-card>
</template>


Js

import { LightningElement,wire,api } from 'lwc';
import fetchAcc from '@salesforce/apex/AccRelatedConC.fetchAcc';
export default class TabInAccordian extends LightningElement {
    data1 = [];
    wiredActivities;
    records = '';
    error;
    @api recordId;
    @wire(fetchAcc,{
        RecId:'$recordId'
    })
    wiredclass({
        data, error
        
    }){
    if(data){
        let dataEditing = JSON.parse(JSON.stringify(data));
        console.log(JSON.stringify(dataEditing));
        this.records = dataEditing.length;
        this.data1 = dataEditing;
        
    }else if(error){
        this.error = error;
    }
    
}
}



Apex

public class AccRelatedConC {
  @AuraEnabled(cacheable=true)
    public static List<Account> fetchAcc (id RecId){
        string query= 'SELECT Id, Name,(select id,Name,AccountId from contacts)'+
                ' FROM Account where Id = :RecId';
        
         return Database.query( query );
        
    }  
}
Please Mark It As Best Answer If It Helps
Thank You!

 
Naveen KNNaveen KN
Another way for displaying contacts related to the accounts here 
https://www.codekiat.com/2020/04/how-to-pass-record-id-from-lightning-web-component-to-apex-controller.html

Naveen
Radha 24Radha 24
Thank you all for your quick response.

I just want to display contacts in account record page.  For this I used @api recordId and used connectedCallback(). 
I am using this component in account record page. But related contacts are not displaying.
Vani ShrivastavaVani Shrivastava
hey i have try this check it out 
html
<template>
<lightning-card>
<lightning-datatable if:true={contacts}
             data={contacts} columns={cols} key-field="id"></lightning-datatable>
   </lightning-card>  
  </template>
js
import { LightningElement,api, wire } from 'lwc';
import getcontact from '@salesforce/apex/account_contact.getcontact';
const Columns = [
    {label: 'Contact Name', fieldName: 'Name'},
    {label: 'Email', fieldName: 'Email'},
    {label: 'Phone', fieldName: 'Phone'},
    {label: 'Account Name', fieldName: 'Account_Name'},
   
    ]// colum for datatable
    //why wirev decorator?  wire is recative in nature  when ever their is change in org data it will automaticaaly reflect in lwc .
export default class Releted_Contact extends LightningElement {
   @api recordId;   // give reacordid of account
   contacts;
    error;
    cols=Columns; //if the Apex method takes a string parameter, don’t pass a string directly. Instead, pass an object that contains a property whose value is a string.
   @wire(getcontact,{val: '$recordId'})wiredContacts({ error, data }) {
    if (data) {
        this.contacts = data;
        this.error = undefined;
        // to show account name
        let currentData = [];
        data.forEach((row)=> { let rowData = {};
rowData.Name = row.Name;
rowData.Email = row.Email;
rowData.Phone = row.Phone;
if (row.Account) {
    rowData.Account_Name = row.Account.Name;
}
currentData.push(rowData);

});
this.contacts = currentData;
       
        //
    } else if (error) {
        this.error = error;
        this.contacts = undefined;
    }
    console.log(data);
    console.log(error);
}

}


apex class

public class account_contact {
     @AuraEnabled(cacheable=true)
  public static List<Contact> getcontact(Id val) {

 return [select  id,Name,Email,Phone,Account.Name from Contact where accountid=:val limit 100 ];
   }
}
o/p: each account you will list of related contact 
User-added image