formie icon indicating copy to clipboard operation
formie copied to clipboard

date value in calculations formula

Open watarutmnh opened this issue 3 years ago • 2 comments

Question

Is there a way to get the date field value as a number using a calculation field? What I want to achieve is to calculate to display the age from the birthday field (date field).

watarutmnh avatar Jul 12 '22 04:07 watarutmnh

Related to https://github.com/verbb/formie/issues/825 and https://github.com/verbb/formie/issues/943 which was originally to address a similar issue, where users wanted to add the source of a dropdown, plus adding a number. But because the value of a Dropdown (or other fields) can't always be trusted to provide a number, we'll need to leave it up to individuals to add this logic.

Or at the very least we can add some checks to try and determine if a variable looks like a number, date, etc. I feel like this might cause unforeseen issues though, as we're assuming a lot. Just because something "looks" like a date, doesn't mean it is. What if the users wants to join two dates as a string, or join two numbers together?

But simple answer is it isn't possible at the moment, sorry. It's difficult to know if you have {date} + 10 - that's +10 what? Days, hours, years? That'll be why we need to provide some extendability for you to add your own logic. Maybe even being able to write JS in the field settings itself.

engram-design avatar Jul 12 '22 07:07 engram-design

I got it! will try with some js. Thanks,

watarutmnh avatar Jul 12 '22 08:07 watarutmnh

There are now JS events that should be a good way to provide this functionality. There are two events you'll want to use:

The beforeEvaluate event to modify the variables that are used in the formula. These will be considered strings grabbed from the <input> elements. You can see how we handle numbers.

// Fetch the Calculations field we want to format values for, a field with the handle `result`
const $field = document.querySelector('[data-field-handle="result"]');

// Listen to every time the formula is evaluated
$field.addEventListener('beforeEvaluate', function(e) {
    // Convert each variable value to a JS Date object, then just use the year.
    Object.keys(e.detail.variables).forEach((index) => {
        let date = new Date(e.detail.variables[index]);

        e.detail.variables[index] = date.getYear();
    });
});

You can also modify the formula too if you require.

The afterEvaluate event to modify the resulting value that's used and shown in the Calculations field as the final result. You can see how we handle numbers.

In your case, you shouldn't need this, as you're casting the source values to Numbers with date.getYear(), and the field will add those number together.

engram-design avatar Sep 04 '22 22:09 engram-design