[SalesForce] lightning datatable (AURA or LWC) can automatically fetch records from database

Is it possible to fetch records automatically from database just by mentioning columns?

Also can we use relationship fields to get data without any processing?

For example CreatedBy.Name ?

Other features like sorting, pagination etc?

Best Answer

Generic component which has following features: (This can be used in both AURA and LWC parent component)

You can find the component here: https://github.com/sasank-sfdcdev/public/tree/master/src/lwc/datatable

  1. Gets data from database automatically. Can use relationship fields also.
  2. Sort functionality (across pages)
  3. Pagination - first, previous, next and last pages
  4. Persistant selection of records across pages. getSelectedRows public method to get selected data.
  5. All events of lightning-datatable plus event while loading data
  6. Cacheable data
  7. Sosl search
  8. Dynamically change data filters

The simplicity of this is such that, you can just put tag, and rest of the things is done by it. Example HTML:

<template>
    <c-datatable config={config}>
    </c-datatable>
</template>

and its JS:

import { LightningElement, track } from 'lwc';

export default class PocTable extends LightningElement {
    config = {
        objectName: "Account",
        tableConfig: {
            columns: [
                { api: 'Name', label: 'Name', fieldName: 'Name', sortable: true },
                { api: 'CreatedDate', label: 'Created On', fieldName: 'CreatedDate', type: 'date', sortable: true },
                { api: 'CreatedBy.Name', label: 'Created By', fieldName: 'CreatedByName', sortable: true }
            ]
        }
    };
}

NOTE: You need add api property in columns which will be used to fetch data from database.

Here is how it will render:

enter image description here


Here is the sample of AURA component:

<aura:component implements="lightning:isUrlAddressable,flexipage:availableForRecordHome,force:hasRecordId,force:lightningQuickAction" access = "GLOBAL">

    <aura:attribute name="config" type="Map" default="{}" />
    <aura:handler name="init" value="{!this}" action="{!c.doInit}" />

    <c:datatable config="{!v.config}" />

</aura:component>

and controller.js,

({
    doInit : function(component, event, helper) {
        component.set("v.config", {
            objectName: "Account",
            tableConfig: {
                columns: [
                    { api: 'Name', label: 'Name', fieldName: 'Name', sortable: true },
                    { api: 'CreatedDate', label: 'Created On', fieldName: 'CreatedDate', type: 'date', sortable: true },
                    { api: 'CreatedBy.Name', label: 'Created By', fieldName: 'CreatedByName', sortable: true }
                ]
            }
        });
    },
})
Related Topic