How to find events between datetimes and display using LWC in Salesforce?

How to find events between datetimes and display using LWC in Salesforce?

Using Salesforce Lightning Web Component and Apex, we can fetch and display events between date time range.

Following code implementation is used for the below use case.

1. Search the users.

2. Select Date-time range.

3. Click Search button to view the Event records that were created during the date-time range selected and belongs to the users selected.

Sample Code:

Apex Class:

public with sharing class CalendarController {
   
    @AuraEnabled
    public static List < OptionWrapper > findUsers( String strName ) {

        List < OptionWrapper > options = new List < OptionWrapper >();
        String strNameFilter = strName + '%';
        system.debug( 'Filter is ' + strNameFilter );
        for ( User objUser : [ SELECT Id, Name FROM User WHERE IsActive = true AND Name LIKE: strNameFilter ] ) {

            OptionWrapper objWrap = new OptionWrapper();
            objWrap.label = objUser.Name;
            objWrap.value = objUser.Id;
            options.add( objWrap );

        }
        return  options;
       
    }

    @AuraEnabled
    public static List< EventWrapper > findEvents( List < String > userIds, DateTime startDT, DateTime endDT ) {

        system.debug( 'User Ids are ' + userIds );
        system.debug( 'Dates are ' + startDT + ' - ' + endDT );
        List< EventWrapper > eventWraps = new List< EventWrapper >();
        for ( Event objEvent : [ SELECT Id, StartDateTime, EndDateTime, Owner.Name, Subject
                                   FROM Event
                                  WHERE OwnerId IN: userIds AND ( StartDateTime >=: startDT OR StartDateTime <=: endDT ) AND ( EndDateTime <=: endDT OR EndDateTime >=: startDT ) ] ) {

            EventWrapper objWrap = new EventWrapper();
            objWrap.Id = objEvent.Id;
            objWrap.StartDateTime = objEvent.StartDateTime.format();
            objWrap.EndDateTime = objEvent.EndDateTime.format();
            objWrap.OwnerName = objEvent.Owner.Name;
            objWrap.Subject = objEvent.Subject;
            eventWraps.add( objWrap );

       }
        return eventWraps;
       
    }

    public class OptionWrapper {

        @AuraEnabled
        public String label;
        @AuraEnabled
        public String value;

    }

    public class EventWrapper {

        @AuraEnabled
        public String Id;
        @AuraEnabled
        public String StartDateTime;
        @AuraEnabled
        public String EndDateTime;
        @AuraEnabled
        public String OwnerName;
        @AuraEnabled
        public String Subject;

    }

}

Lightning Web Component:

HTML:

<template>
    <div class="slds-box slds-theme_default">
        <div class="slds-grid slds-gutters">
            <div class="slds-col slds-size_1-of-2">
                <lightning-input type="text" label="Enter the Name to search" name="username" onchange={handleInputChange}></lightning-input>
                <div class="slds-p-top_small slds-p-bottom_small">
                    <lightning-button onclick={findUsers} label="Find Users" variant="brand"></lightning-button>
                </div>
                <lightning-dual-listbox options={options}   
                                        label="Select Users"
                                        source-label="Available"
                                        selected-label="Selected"
                                        onchange={handleChange}></lightning-dual-listbox>
            </div>
            <div class="slds-col slds-size_1-of-2">
                <lightning-input type="datetime" label="Start Date/Time" name="stdt" onchange={handleInputChange}></lightning-input>
                <lightning-input type="datetime" label="End Date/Time" name="enddt" onchange={handleInputChange}></lightning-input>
            </div>
        </div>
        <div class="slds-p-top_small slds-p-bottom_small">
            <lightning-button onclick={findEvents} label="Find Events" variant="brand"></lightning-button>
        </div>
        <div>
            <lightning-datatable key-field="Id" 
                                data={events} 
                                columns={columns} 
                                hide-checkbox-column="true" 
                                show-row-number-column="false"></lightning-datatable> 
        </div>
     </div>
   
</template>

JavaScript:

import { LightningElement, track } from 'lwc';
import fetchUsers from '@salesforce/apex/CalendarController.findUsers';
import findEvents from '@salesforce/apex/CalendarController.findEvents';

const columns = [ 
    { label: 'Subject', fieldName: 'Subject' }, 
    { label: 'Start', fieldName: 'StartDateTime' },
    { label: 'End', fieldName: 'EndDateTime' }, 
    { label: 'Owner', fieldName: 'OwnerName' }, 
];

export default class Calendar extends LightningElement {

    @track options = [];
    @track valuesCheck = [];
    @track values = [];
    @track events;
    @track columns = columns;
    @track strName;
    @track startDT;
    @track endDT;

    findUsers( event ) {

        var strSearchKey = this.strName;
        console.log( 'Search Key is ' + strSearchKey );
        fetchUsers( { strName:strSearchKey } )  
        .then(result => {

            console.log( 'Result is ' + JSON.stringify( result ) );            
            this.options = [];
            if ( this.values ) {

                console.log( 'Values are ' + this.values );
                for ( var j = 0; j < this.values.length; j++ )
                    this.options.push( this.values[ j ] );

            }
           
            for ( var i = 0; i < result.length; i++ ) {

                if ( !this.valuesCheck.includes( result[ i ].value ) ) {

                    this.options.push( result[ i ] );

                }

            }

        })
        .catch(error => {

            console.log( 'Error is ' + JSON.stringify( error ) );

        });

    }

    handleChange( event ) {
       
        this.valuesCheck = [];
        this.values = [];
        const selectedOptionsList = event.detail.value;
        console.log( 'Selected Options are ' + JSON.stringify( selectedOptionsList ) );
        for ( var i = 0; i < selectedOptionsList.length; i++ ) {

            this.valuesCheck.push( selectedOptionsList[ i ] );
            for ( var j = 0; j < this.options.length; j++ ) {

                if ( this.options[ j ].value == selectedOptionsList[ i ] )
                    this.values.push( this.options[ j ] );

            }

        }
       
    }

    findEvents() {

        var userIds = [];
        for ( var i = 0; i < this.values.length; i++ )
            userIds.push( this.values[ i ].value );
        console.log( 'User Ids are ' + userIds );
        var varST = this.startDT;
        var varET = this.endDT;
        findEvents( { userIds:userIds, startDT:varST, endDT:varET } )  
        .then(result => {

            console.log( 'Event Result is ' + JSON.stringify( result ) );  
            /*for ( var i = 0; i < result.length; i++ ) {
               
                if ( result[ i ].Owner )
                    result[ i ].OwnerName = result[ i ].Owner.Name;

            }*/
            this.events = result;

        })
        .catch(error => {

            console.log( 'Error is ' + JSON.stringify( error ) );

        });

    }

    handleInputChange( event ) {

        if ( event.target.name == 'username' )
            this.strName = event.target.value;
        else if ( event.target.name == 'stdt' )
            this.startDT = event.target.value;
        else if ( event.target.name == 'enddt' )
            this.endDT = event.target.value;

    }

}

JavaScript-meta.xml:

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

Output:

Leave a Reply