Create Custom Datatype in Lightning Datatable - LWC

 Purpose:

The lightning-datatable component formats data based on the type you specify for the column.

Before you create your own data type, check the standard data types to see if one meets your requirements. You can use type attributes to customize the output for many types. The standard data types are:

  • action
  • boolean
  • button
  • button-icon
  • currency
  • date
  • date-local
  • email
  • location
  • number
  • percent
  • phone
  • text (default)
  • url
For more information on standard data types and their type attributes, see the lightning-datatable reference documentation.

Additionally, consider SLDS styling hooks before you create your own data type. SLDS styling hooks help you customize a supported data type across the shadow DOM. For example, you can use an SLDS styling hook to apply a different color on a button data type.

NOTE Custom data types don’t support dispatching custom events.

Define Your Custom Type by Extending LightningDatatable:

Create your own data type to implement a custom cell, such as a delete row button or an image, or even a custom text or number display. You can also apply a custom class for each row on your custom data type.

To define and use a custom data type, extend the LightningDatatable class of the lightning-datatable component in a new component.

NOTE You can extend from LightningDatatable only to create a datatable with custom data types. In all other cases, extending any class besides LightningElement to create a Lightning web component isn’t supported.

Create a Lightning web component and define your type in an HTML template in the component folder. The template can contain the complete UI for a simple data type that doesn’t require JavaScript. The template can also embed a component that you define in another folder. For example, use a separate component when you want to include logic that determines what to display.

Let’s look at the folder structure for the component myCustomTypeDatatable, which defines two custom types.

myCustomTypeDatatable
   ├──customName.html
   ├──customNumber.html
   ├──myCustomTypeDatatable.js
   └──myCustomTypeDatatable.js-meta.xml
In your JavaScript file myCustomTypeDatatable.js, extend the LightningDatatable class and specify your type’s name and template file. This example creates a custom name type and custom number type using the customName.html and customNumber.html templates.

The names of the type and template don't have to match. The example uses customName for both the type name and the template file name. We recommend that you import the templates with different names to make it clear where you specify the type name and template name.

//myCustomTypeDatatable.js
import LightningDatatable from 'lightning/datatable';
import customNameTemplate from './customName.html';
import customNumberTemplate from './customNumber.html';

export default class MyCustomTypeDatatable extends LightningDatatable {
    static customTypes = {
        customName: {
            template: customNameTemplate,
            standardCellLayout: true,
            typeAttributes: ['accountName'],
        },
        customNumber: {
            template: customNumberTemplate,
            standardCellLayout: false,
            typeAttributes: ['status'],
        }
        // Other types here
    }
}

NOTE You can extend from LightningDatatable only to create custom data types.

Pass in the following properties to the customTypes object:

CUSTOM TYPE PROPERTYTYPEDESCRIPTION

template

string

The name of your type's imported HTML template.

typeAttributes

array

The comma-separated list of attributes to pass to the custom data template. Access your data using the typeAttributes.attributeName syntax.

standardCellLayout

boolean

Specifies whether the standard layout is used. The default is false.

The standard layout is used by all standard data types.

The default layout for custom data types is the bare layout. See Customize Data Type Layout and Styles.

You can use the standardCellLayout to style cells for your custom data type to make them look similar to the standard data types.

The standardCellLayout also supports accessibility and keyboard navigation.

Create a Custom Data Template:

In your custom data template customName.html, add the markup for your data type. This example creates a custom type that renders a text label using a lightning-badge component.

<!--customName.html-->
<template>
    <lightning-badge 
        label={typeAttributes.accountName}
        icon-name="standard:account">
    </lightning-badge>
</template>

The customNumber.html template uses the default bare layout because myCustomTypeDatatable.js sets standardCellLayout: false for customNumber. You can add your own styling. This example adds a small padding around the cell and floats the number to the right. An icon is displayed if the number matches criteria specified in the data definition.

<!--customNumber.html-->
<template>
    <div class="slds-p-around_x-small">
        <lightning-formatted-number value={value} class="slds-float_right"></lightning-formatted-number>
        <lightning-icon icon-name={typeAttributes.status} alternative-text="Employer Status"></lightning-icon>
    </div>
</template>
TIP These example custom data types are simple and can be expressed with only HTML. If your custom type is more complex, create a separate component with JavaScript, HTML template, and XML configuration file. Use the custom data HTML template as a container for the component. A separate component is used in Edit Template Example for Custom Data Types.

Implement Your Data Table with the Custom Types:

Let’s implement a data table that uses the custom types. The first column displays the account name using the custom type we created in the previous section. The fieldName property matches the Name field on the account object.


Display 10 account records in the data table using an Apex controller.

public with sharing class AccountController {
    @AuraEnabled(cacheable=true)
    public static List<Account> getAccountList() {
        return [SELECT Id, Name, Industry, NumberOfEmployees FROM Account WITH SECURITY_ENFORCED LIMIT 10];
    }
}

To implement the custom type datatable, create a wrapper component to contain your extended datatable component, define the datatable’s columns, and fetch data. Here we use myDatatable as the wrapper.

When defining the columns, you can pass in SLDS utility classes or your own classes using the cellAttributes property.


/* myDatatable.js */
import { LightningElement, wire, track } from 'lwc';
import getAccountList from '@salesforce/apex/AccountController.getAccountList';

const COLS = [
    { label: 'Account Name', type: 'customName',
     typeAttributes: {
        accountName: { fieldName: 'Name' }
    },
    },
    { label: 'Industry', fieldName: 'Industry', 
    cellAttributes: {
        class: {fieldName: 'industryColor'},
    }
    },
    { label: 'Employees', type: 'customNumber', fieldName: 'NumberOfEmployees',
     typeAttributes: {
        status: {fieldName: 'status'}
    },
    cellAttributes: {
        class: 'slds-theme_alert-texture'
    }
}];

export default class MyDatatable extends LightningElement {
    columns = COLS;
    @track accounts = [];

    @wire(getAccountList)
    wiredAccounts({error, data}) {
        if (error) {
            // Handle error
        } else if (data) {
            // Process record data
            this.accounts = data.map((record) => {
                let industryColor = record.Industry === 'Energy' ? 'slds-text-color_success': '';
                let status = record.NumberOfEmployees > 10000 ? 'utility:ribbon' : '';
                return {...record, 
                    'industryColor': industryColor,
                    'status': status
                }
            });
            
        }
    }
}

myDatatable.js shows several ways to apply styling on a custom cell. The Industry column uses the slds-text-color_success class only if the field value matches Energy. The NumberOfEmployees column uses the slds-theme_alert-texture class on all rows of the column. Additionally, the customNumber type that’s used for the NumberOfEmployees column includes layout and padding classes implemented directly in the customNumber.html markup.

Next, pass the data returned by the getAccountList Apex controller to the data attribute in your custom type datatable component.


<!--myDatatable.html-->
<template>
    <c-my-custom-type-datatable
        key-field="Id"
        data={accounts}
        columns={columns}
        show-row-number-column>
    </c-my-custom-type-datatable>
</template>
Happy coding... 😊

Post a Comment

Previous Post Next Post