Ad Code

How to display multiple object records in a single lightning data table of Salesforce

Lightning datatable example

In this blog post, find a sample code to display multiple objects' data in a single lightning-datatable base component in the Salesforce lightning CRM.

In this example, Subject and Activity Date fields of Task and Event objects are wrapped into a single list in the Apex and passed to the lightning web component.

Create a new Apex class


public class TaskAndEventController {
    public static list<TaskAndEventWrapper> getTaskandEvents(){
        list<TaskAndEventWrapper> taskAndEventRecords = new list<TaskAndEventWrapper>();
        string userId = UserInfo.getUserId();      
        List<Task> taskList = [SELECT Subject, ActivityDate FROM Task WHERE OwnerId=:userId ORDER BY ActivityDate];
        List<Event> eventList = [SELECT Subject, ActivityDate FROM Event WHERE OwnerId=:userId ORDER BY ActivityDate];   
        for(Task t: taskList){
            TaskAndEventWrapper tWrap = new TaskAndEventWrapper();
            tWrap.Subject = t.Subject;
            tWrap.ActivityDate = t.ActivityDate;
        for(Event e: eventList){
            TaskAndEventWrapper eWrap = new TaskAndEventWrapper();
            eWrap.Subject = e.Subject;
            eWrap.ActivityDate = e.ActivityDate;
        system.debug('taskAndEventRecords >> ' + taskAndEventRecords);
        return taskAndEventRecords;
    public class TaskAndEventWrapper{
        public string Subject{get; set;}
        public Date ActivityDate{get; set;}

Create a new lightning web component


    <lightning-card title="Related Activities ">
        <lightning-datatable data={activities} columns={columns} key-field="Id">


import { LightningElement, api, wire, track } from 'lwc';
import getActivities from
export default class TaskAndEvents extends LightningElement {
    @api recordId;
    @track activities;
    @track columns = [
        { label: 'Subject', fieldName: 'Subject', type: 'text' },
        { label: 'Activity Date', fieldName: 'ActivityDate', type: 'date' }
    WireActivityRecords({error, data}){
            this.activities = data;
            this.error = undefined;
            this.error = error;
            this.activities = undefined;


<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="">

Ensure that the variable name in the Apex wrapper class matches with the
columns variable fieldName attribute value of the LWC JavaScript file.

Apex wrapper

Save or deploy the lightning web component to the sandbox, add the new component to the Flexi page and test the functionality.

It should display the records from task and event objects as shown below

Activities data in a single data table

If you find any issues in implementing this, debug your lightning web component and add your queries or feedback in the comments section below.

Until next time... 

Post a Comment