1

I have a very simple LWC(just learning) I am trying to create something like a datatable(.net) or like the old visualforce page(PageBlockSection) like structure such as the related list and display it.

I can get data to display using the template however instead of just displaying it i want it displayed in a grid. Is there a very simple example anywhere?

Apex Class

public with sharing class ContactData {
@AuraEnabled(cacheable=true)

public static List<Contact> getContacts(String accId) {
    return [SELECT Id, Name ,Email, Phone, Account.Name from Contact where AccountId = :accId];
}

}

HTML

<template>
    <lightning-card title="Account Collection" icon-name="custom:custom14">
<div class="boarder"> 
    <template if:true={myContacts.data}>

            <ul class="slds-list_ordered">



                    <template for:each={myContacts.data} for:item="contact">


                    <li key={contact.Id}>
                            {contact.Name}
                            {contact.Email}

                    </li> 

                    </template>

        </ul>




    </template>

</div>

JavaScript

import { LightningElement,api,wire } from 'lwc';
//Reads the Controller Class Get Contacts. Must Specify the file path - Class and Function returned. 
import getContacts from '@salesforce/apex/ContactData.getContacts';

export default class RecordIdExample extends LightningElement {
//Passes a Record Id from the page to the Class. 
 @api recordId;
@wire(getContacts, {accId:'$recordId' })
//returns MyContacts as a variable that is then used in the HTML.
  myContacts;
}

3 Answers 3

1

This could be done in a couple of ways. If you are wanting a data table, then you would do as already mentioned https://developer.salesforce.com/docs/component-library/bundle/lightning-datatable/example

HTML

<template>
    <lightning-card title="Contacts" icon-name="standard:contact"> 
           <template if:true={data}>
                   <lightning-datatable data={data}
                                    columns={columns}
                                    key-field="id"
                                    onrowselection={getSelectedRecords}>
                    </lightning-datatable>
           </template>
   </lightning-card>   

JS

import {LightningElement, track, wire, api } from 'lwc';

// importing apex class methods
import getContacts from '@salesforce/apex/LWCContactController.getContacts';


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

    }
];

export default class contactTableLWC extends LightningElement {

    @track data;
    @track columns = columns;
    @track isTrue = false;
    @track recordsCount = 0;
    @api recordId;



    // retrieving the data using wire service
    @wire(getContacts, {conId: '$recordId'})
    contacts(result) {
        this.refreshTable = result;
        if (result.data) {
            this.data = result.data;
            this.error = undefined;

        } else if (result.error) {
            this.error = result.error;
            this.data = undefined;
        }
    }

}


If it is not a data table that you are looking for, then you can utilize the LDS grid system to control how the elements are displayed in the component. https://www.lightningdesignsystem.com/utilities/grid/#site-main-content

HTML Example


<template>
    <lightning-card title="Account Collection" icon-name="custom:custom14">
<div class="boarder"> 
    <template if:true={myContacts.data}>
       <div class="slds-grid slds-wrap">
          <template for:each={myContacts.data} for:item="contact">
             <div key={contact.Id}>  
                <div key={contact.Id} class="slds-col">  
                  {contact.Name}      
                </div> 
                <div class="slds-col">  
                  {contact.Email}    
                </div> 
             </div> 
           </template>
      </div>
    </template>
</div>
2
  • I found that with the DataTable you cannot get Account__r.Name. Is there a way to get the parent name on the Grid easily?
    – CodeMonger
    Jan 31, 2020 at 13:07
  • To my knowledge it is not possible to display traversed items in the the datatable without mapping them. Try doing something similar to this: @wire(getOpportunityLineItems, {oppId: '$recordId'}) lineitems(result) { this.refreshTable = result; if (result.data) { this.data = result.data.map(row=>{ return{...row, productName: row.Product2.Name} }) this.error = undefined; } else if (result.error) { this.error = result.error; this.data = undefined; } }
    – Jordan
    Jan 31, 2020 at 15:53
0

I found a simple Example for anyone else that has the same issue I did.

JavaScript:

<template>
    <lightning-card title="Account Collection" icon-name="custom:custom14">
<div class="boarder"> 
    <template if:true={myContacts.data}>

        <lightning-datatable
            key-field="Id"
            data={myContacts.data}
            columns={columns}
            onsave={handleSave}
            draft-values={draftValues}>
        </lightning-datatable>


    </template>

</div>

HTML

<template>
    <lightning-card title="Account Collection" icon-name="custom:custom14">
<div class="boarder"> 
    <template if:true={myContacts.data}>

        <lightning-datatable
            key-field="Id"
            data={myContacts.data}
            columns={columns}
            onsave={handleSave}
            draft-values={draftValues}>
        </lightning-datatable>


    </template>

</div>
</lightning-card>
</template>
1
  • JS file is missing above and is a duplicate of HTML example.
    – DustinB
    Dec 8, 2020 at 16:38
0

Working for me, use this code-- ContactController.cls----------

public with sharing class ContactController {
    @AuraEnabled(cacheable=true)
    public static List<Contact> getContacts() {
        return [
            SELECT FirstName,LastName,Email
            FROM Contact
            WITH SECURITY_ENFORCED
        ];
    }
}

<template>
<lightning-card>
    <lightning-record-form
        object-api-name={objectApiName}
        fields={fields}
        onsuccess={handleSuccess}>
    </lightning-record-form>
</lightning-card>
---------------
import { LightningElement } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import CONTACT_OBJECT from '@salesforce/schema/Contact';
import FIRSTNAME_FIELD from '@salesforce/schema/Contact.FirstName';
import LASTNAME_FIELD from '@salesforce/schema/Contact.LastName';
import EMAIL_FIELD from '@salesforce/schema/Contact.Email';

export default class ContactCreator extends LightningElement {
    objectApiName = CONTACT_OBJECT;
    
    fields = [FIRSTNAME_FIELD, LASTNAME_FIELD, EMAIL_FIELD];
    handleSuccess(event) {
        const toastEvent = new ShowToastEvent({
            title: "Contact created",
            message: "Record ID: " + event.detail.id,
            variant: "success"
        });
        this.dispatchEvent(toastEvent);
    }
}

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .