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
Danny BoyleDanny Boyle 

Auto-calculating lightning datatable columns based on input received

We have a lightning data table built in LWC, which has 2 columns - start date and end date. Start Date is going to be the first date of any month and the End Date would be the last date of the same month. However, we expect that as soon as the first start date has been entered manually, the rest of the start and end dates be calculated automatically in the same fashion. And the calculation should happen for next 12 months. The values in the data table are later being stored in the databaseUser-added image
Shivani Kolhe 11Shivani Kolhe 11

To calculate the subsequent Start and End Dates automatically for the next 12 months, you can use JavaScript. Here's a sample code snippet:
// Assuming your initial start date is stored in this.startDate
let startDate = new Date(this.startDate);
let data = []; // Your datatable data array

for (let i = 0; i < 12; i++) {
    let endDate = new Date(startDate);
    endDate.setMonth(endDate.getMonth() + 1);
    endDate.setDate(0); // This sets the day to the last day of the month

    data.push({
        startDate: startDate.toISOString().split('T')[0], // Convert to YYYY-MM-DD format
        endDate: endDate.toISOString().split('T')[0]
    });

    // Update startDate for the next iteration
    startDate = endDate;
    startDate.setDate(startDate.getDate() + 1); // Set to the first day of the next month
}

// Update your datatable data
this.yourDataTableData = data;

This code calculates the Start and End Dates for the next 12 months based on the initial Start Date entered by the user and stores them in the data array. Bind your datatable to the yourDataTableData array, which contains the calculated Start and End Dates. When you update this array, the datatable should automatically reflect the changes
Finally, when you're ready to store the data in the database, you can send the yourDataTableData array to your Apex controller or JavaScript function for further processing and database insertion.

 

Let me know if this works!