Wednesday, May 3, 2023

Display Contacts with Account detail Table In LWC

Apex Class :

public with sharing class AccountsAndContactsTabelLWCCtr {
    public AccountsAndContactsTabelLWCCtr() {
       
    }
    @AuraEnabled(cacheable=true)
    public static List<contact> getAccsAndCons(){
        try {
            return [select id, Name, Email, Accountid, Account.Name from contact where email != null limit 20 ];
        } catch (Exception e) {
            throw new AuraHandledException(e.getMessage());
        }
    }
}

meta.xml:

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>56.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__RecordPage</target>
    </targets>
</LightningComponentBundle>

JS :

import { LightningElement ,api, wire, track} from 'lwc';
import getAccsCons from '@salesforce/apex/AccountsAndContactsTabelLWCCtr.getAccsAndCons'

const columns = [
    { label: 'Contact Name', fieldName: 'Name' },
    { label: 'Contact Email', fieldName: 'Email' },
    { label: 'Account Name', fieldName: 'AccName' }
];
export default class AccountsAndContactsTabelLWC extends LightningElement {
    @api recordId;
    @track records;
    @track dataNotFound;
    columns = columns;
    @wire (getAccsCons)
    wireRecord({data,error}){
        if(data){
            let tempRecords = JSON.parse( JSON.stringify( data ) );
            console.log('tempRecords : '+tempRecords);
            tempRecords = tempRecords.map( row => {
                console.log('Email : '+row.Email);
                return {Name: row.Name,Email: row.Email, AccName: ( row.Account ? row.Account.Name : null ) };
            })
           
            this.records = tempRecords;
            console.log('Data : '+tempRecords);
            this.error = undefined;
            this.dataNotFound = '';
            if(this.records == ''){
                this.dataNotFound = 'There is no Contact found related to Account name';
            }
 
           }else{
               this.error = error;
               this.data=undefined;
           }
    }
   
}

 HTML:

<template>
    <lightning-card variant="narrow" icon-name="standard:account" title="Contacts">
        <lightning-datatable
                key-field="Id"
                data={records}
                columns={columns}
                hide-checkbox-column="false">
        </lightning-datatable>
    </lightning-card>
</template>

No comments:

Post a Comment