function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Siri Deva Singh KhalsaSiri Deva Singh Khalsa 

lightning-datatable - use field values of current record to preselect rows

Hi All,

I'm trying to use a lightning-datatable component to pull in activity history on a lead record page. I want to see activity only WHERE WhoId = currentRecord.Id OR WhoId = currentRecord.ContactId__c

I test successfully until the point where I try to access the recordId in my controller. Apparently @auraEnabled methods cannot accesss ApexPages.StandardController objects.

How do I preselect out my ActivityHistory in the data table so that I only see records based on certain crtieria for the whoId? Any advice would be most appreciated.

html:
<template>
    <lightning-card title="Sorting Data in Lightning Datatable in LWC" icon-name="standard:lead" > <br/>
        <div style="width: auto;">
            <template if:true={data}>
                <lightning-datatable data={data}
                                     columns={columns}
                                     key-field="id"
                                     sorted-by={sortBy}
                                     sorted-direction={sortDirection}
                                     onsort={handleSortdata}
                                     hide-checkbox-column="true"></lightning-datatable>
            </template>

        </div>
    </lightning-card>
</template>
apex controller
public inherited sharing class dataTableController {
    
    @AuraEnabled(Cacheable = true)
    public static List<ActivityHistory> getActivity(){
        List<Lead> leadQueryList;  
        List<ActivityHistory> activityList = new List<ActivityHistory>(); //variable to hold the list of activitiyhistories
        
        leadQueryList = [                           //query all activity history related to the lead (return list of leads w nested ah lists)
                        SELECT  Id,
                                (SELECT
                                    Id, 
                                    Subject, 
                                    ActivityDate, 
                                    OwnerId,
                                    Activity_Type__c                                                                                                                                    
                                 FROM ActivityHistories)
                        FROM Lead
                        WHERE Id = :leadId]; 
        for (Lead ld : leadQueryList) {               //loop through lead list
            if(!ld.ActivityHistories.isEmpty()){
                for (ActivityHistory h: ld.ActivityHistories){
                    activityList.add(h);
                }
            }
        }
        return activityList;
    }
}


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

// importing apex class methods
import getActivity from '@salesforce/apex/dataTableController.getActivity';

// datatable columns with row actions
const columns = [
    {
        label: 'Date',
        fieldName: 'ActivityDate',
        sortable: "true"
    }, {
        label: 'Activity Type',
        fieldName: 'Activity_Type__c',
        sortable: "true"
    }, {
        label: 'Subject',
        fieldName: 'Subject',
        sortable: "true"
    }, {
        label: 'Assigned',
        fieldName: 'OwnerId',
        sortable: "true"
    },
];

export default class DataTableWithSortingInLWC extends LightningElement { 
    // reactive variable
    @track data;
    @track columns = columns;
    @track sortBy;
    @track sortDirection;
    @api recordId;

    // retrieving the data using wire service
    @wire(getActivity)
    activities(result) {
        if (result.data) {
            this.data = result.data;
            this.error = undefined;

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

    handleSortdata(event) {
        // field name
        this.sortBy = event.detail.fieldName;

        // sort direction
        this.sortDirection = event.detail.sortDirection;

        // calling sortdata function to sort the data based on direction and selected field
        this.sortData(event.detail.fieldName, event.detail.sortDirection);
    }

    sortData(fieldname, direction) {
        // serialize the data before calling sort function
        let parseData = JSON.parse(JSON.stringify(this.data));

        // Return the value stored in the field
        let keyValue = (a) => {
            return a[fieldname];
        };

        // cheking reverse direction 
        let isReverse = direction === 'asc' ? 1: -1;

        // sorting data 
        parseData.sort((x, y) => {
            x = keyValue(x) ? keyValue(x) : ''; // handling null values
            y = keyValue(y) ? keyValue(y) : '';

            // sorting values based on direction
            return isReverse * ((x > y) - (y > x));
        });

        // set the sorted data to data table data
        this.data = parseData;

    }
}




User-added image

 
Best Answer chosen by Siri Deva Singh Khalsa
David Zhu 🔥David Zhu 🔥
You may modify your code a bit.
1. in Apex controller, change the method getActivity
public static List<ActivityHistory> getActivity(string leadId){
2. in lwc js controller, change the wire method by passing recordId.
Change this line: 
@wire(getActivity)

to @wire(getActivity,{leadId: '$recordId'})

All Answers

David Zhu 🔥David Zhu 🔥
You may modify your code a bit.
1. in Apex controller, change the method getActivity
public static List<ActivityHistory> getActivity(string leadId){
2. in lwc js controller, change the wire method by passing recordId.
Change this line: 
@wire(getActivity)

to @wire(getActivity,{leadId: '$recordId'})
This was selected as the best answer
Siri Deva Singh KhalsaSiri Deva Singh Khalsa
Thank you, David. It worked. 
I've hit on road block on the second part of use case though. Our leads are pre-associated with a contact record through a lookup relationship field Lead.ContactId__c. I would like to additionally display activity history assoicated with this contact in the data table.

In particular, I don't feel sure about the syntax for js line:  
@wire(getActivity, {leadId: '$recordId', contactId: lead.CONTACTID_FIELD })

My code below will deploy, but the table turns up blank. Any thoughts?



apex controller
public inherited sharing class dataTableController {
    
    @AuraEnabled(Cacheable = true)
    public static List<ActivityHistory> getActivity(string leadId, string contactId){
        List<Lead> leadQueryList;
        List<Contact> ctactQueryList;  
        List<ActivityHistory> activityList = new List<ActivityHistory>(); //variable to hold the list of activitiyhistories
        
        leadQueryList = [                           //query all activity history related to the lead (return list of leads w nested ah lists)
                        SELECT 	Id,
                                (SELECT
                                    Id, 
                                 	Subject, 
                                 	ActivityDate, 
                                 	OwnerId,
                                    Activity_Type__c                                                                 	                                 	                            
                                 FROM ActivityHistories)
                        FROM Lead
                        WHERE Id = :leadId];

        ctactQueryList = [                           //query all activity history related to the ctact (return list of ctact w nested ah lists)
                        SELECT 	Id,
                                (SELECT
                                    Id, 
                                 	Subject, 
                                 	ActivityDate, 
                                 	OwnerId,
                                    Activity_Type__c                                                                 	                                 	                            
                                 FROM ActivityHistories)
                        FROM Contact
                        WHERE Id = :contactId];

        for (Lead ld : leadQueryList) {               //loop through lead list
            if(!ld.ActivityHistories.isEmpty()){
                for (ActivityHistory h: ld.ActivityHistories){
                    activityList.add(h);
                }
            }
        }

        for (Contact c : ctactQueryList) {               //loop through ctact list
            if(!c.ActivityHistories.isEmpty()){
                for (ActivityHistory h: c.ActivityHistories){
                    activityList.add(h);
                }
            }
        }
        return activityList;
    }
}

js
 
import {LightningElement, wire, track, api} from 'lwc';
import { getRecord, getFieldValue } from 'lightning/uiRecordApi';

import CONTACTID_FIELD from '@salesforce/schema/Lead.contactId__c';

// importing apex class methods
import getActivity from '@salesforce/apex/dataTableController.getActivity';

// datatable columns with row actions
const columns = [
    {
        label: 'Date',
        fieldName: 'ActivityDate',
        sortable: "true"
    }, {
        label: 'Activity Type',
        fieldName: 'Activity_Type__c',
        sortable: "true"
    }, {
        label: 'Subject',
        fieldName: 'Subject',
        sortable: "true"
    }, {
        label: 'Assigned',
        fieldName: 'OwnerId',
        sortable: "true"
    },
];

export default class DataTableWithSortingInLWC extends LightningElement { 
    // reactive variable
    @track data;
    @track columns = columns;
    @track sortBy;
    @track sortDirection;
    @api recordId;

    // retrieving the data using wire service
    @wire(getRecord,{recordId: '$recordId' , fields: CONTACTID_FIELD})
    lead;

    @wire(getActivity, {leadId: '$recordId', contactId: lead.CONTACTID_FIELD })

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

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

    handleSortdata(event) {
        // field name
        this.sortBy = event.detail.fieldName;

        // sort direction
        this.sortDirection = event.detail.sortDirection;

        // calling sortdata function to sort the data based on direction and selected field
        this.sortData(event.detail.fieldName, event.detail.sortDirection);
    }

    sortData(fieldname, direction) {
        // serialize the data before calling sort function
        let parseData = JSON.parse(JSON.stringify(this.data));

        // Return the value stored in the field
        let keyValue = (a) => {
            return a[fieldname];
        };

        // cheking reverse direction 
        let isReverse = direction === 'asc' ? 1: -1;

        // sorting data 
        parseData.sort((x, y) => {
            x = keyValue(x) ? keyValue(x) : ''; // handling null values
            y = keyValue(y) ? keyValue(y) : '';

            // sorting values based on direction
            return isReverse * ((x > y) - (y > x));
        });

        // set the sorted data to data table data
        this.data = parseData;

    }
}

html
 
<template>
    <lightning-card title="Sorting Data in Lightning Datatable in LWC" icon-name="standard:lead" > <br/>
        <div style="width: auto;">
            <template if:true={data}>
                <lightning-datatable data={data}
                                     columns={columns}
                                     key-field="id"
                                     sorted-by={sortBy}
                                     sorted-direction={sortDirection}
                                     onsort={handleSortdata}
                                     hide-checkbox-column="true"></lightning-datatable>
            </template>

        </div>
    </lightning-card>
</template>

​​​​​​​
 
David Zhu 🔥David Zhu 🔥
I would keep the defination of getActivity method
public static List<ActivityHistory> getActivity(string leadId) and lwc js code.

Instead, in the getActivity method, you may add a soql query to get the contactId before quering activityHistory on Contact record. I feel that would be simpler.

Lead l = [Select Contact__c from Lead where Id =:leadId];
string contactId = l.Contact__c;



   ctactQueryList = [                           //query all activity history related to the ctact (return list of ctact w nested ah lists)
                        SELECT     Id,
                                (SELECT
                                    Id, 
                                     Subject, 
                                     ActivityDate, 
                                     OwnerId,
                                    Activity_Type__c                                                                                                                                      
                                 FROM ActivityHistories)
                        FROM Contact
                        WHERE Id = :contactId];
 
Siri Deva Singh KhalsaSiri Deva Singh Khalsa
Agreed. A much simpler route. Thank you again. -SD Michael Rencewicz Data Analyst | Castle Group 12270 SW 3rd Street, Suite 200, Plantation, FL 33325 P: 954-660-1823 | C: | F: mrencewicz@castlegroup.com | www.castlegroup.com