Category: UI Widgets
Updated

This solution is summarized from an archived support forum post. This information may have changed. If you notice an error, please let us know in Discord.

Complete Newbie - How to connect buttons to Datepicker?

Issue

I was given a tool to connect data reporting from SQL DB to HubSpot. I needed to add buttons to change the dates of two datepickers in the app when clicked. However, I am not familiar with JavaScript. I want to know if it's possible to assign dates automatically with a single click on the button. The layout is shown in the picture.

Resolution

The task at hand is to add buttons to an Appsmith app that will change the date range in two datepicker widgets. The desired date ranges are last 7 days, last two weeks, and last month. The solution involves using the moment library to calculate the appropriate dates based on the current date, and the storeValue() method to update the datepicker widgets.

First, the To datepicker should be set to the current date. Then, to calculate the From datepicker value based on the desired time range, the moment library can be used to subtract the appropriate number of days or weeks from the current date. For example, to get the date value for the last 7 days, we can use moment().subtract(7, 'days').

Next, the storeValue() method can be used to update the datepicker widgets with the calculated date values. The datepicker widgets should have their values linked to the app’s global store. To update the value of a widget, use storeValue('storeValueName', 'widgetProperty', 'newvalue').

Here is an example code snippet that sets the To datepicker to the current date and the From datepicker to the date 7 days ago:

const toDate = moment().format('YYYY-MM-DD');
const fromDate = moment().subtract(7, 'days').format('YYYY-MM-DD');
storeValue('dateRange', 'fromDate', fromDate);
storeValue('dateRange', 'toDate', toDate);

This code can be added to the onClick handler of the last 7 days button to update both datepickers with one click. The same logic can be applied to the other two buttons to set the date range for the last two weeks and last month.