Expand my Community achievements bar.

July 31st AEM Gems Webinar: Elevate your AEM development to master the integration of private GitHub repositories within AEM Cloud Manager.

FormCalc: if date2 > date1 --> show/hide textfield (how?)


Level 2


I am currently creating a first aid record/employee's first report of illness/injury form. According to Workers' Compensation legislation, incidents must be reported within 24 hours. In the form, I have two date fields, DateOfInjury and DateReported, respectively. The display and validation patterns for these are set to "MMMM D, YYYY".

I also have a text field in which the user can state the reason the incident was not reported on the it occurred. Essentially, if the values of the dates entered match, there is no reason to indicate why there was a discrepancy, so DateDiscrepancy would remain hidden. However, if there is a discrepancy (i.e., DateReported > DatedOfInjury), we want DateDiscrepancy to be visible and for an alert to appear, prompting the user to enter something in the DateDiscrepancy textfield.

(If we want to get really fancy, we could also create another condition that makes DateDiscrepancy required if var diff > 0 and throw another error if DateDiscrepancy is null under this condition.)

Here is the solution, invoked by a Calculate event. I've included a lot of comments to help those who, like me, fumble around in the dark until they figure it out.

form1.#subform[0].Section1.IncidentDetails.IncidentSpecs.DateReported::exit - (FormCalc, client)

// First things first. To perform numeric comparisons, we need to convert the raw values

// of each date field to numeric date. To do that, we use the Date2Num function.

// Then, we need to assign a variable, diff, that will hold the value of the difference

// between the two dates.

var diff = Date2Num(DateReported.rawValue, "YYYY-MM-DD") - Date2Num(DateOfInjury.rawValue, "YYYY-MM-DD");

// Wwe are going to compare DateReported against DateOfInjury to determine

// whether there is a difference between the two dates.

if (diff > 0) then

// If there is a difference, we will display an alert to prompt the user to enter the data

// required.

     xfa.host.messageBox("Please state why this incident was not reported on the date it occurred.")


// We will also display the text field in which to enter that data.

     DateDiscrepancy.presence = "visible"

// We need to specify that this is a REQUIRED field and cannot be left blank.

     DateDiscrepancy.mandatory = "error"

     DateDiscrepancy.mandatoryMessage = "You must explain why the incident was not reported on the date it occurred; this field cannot be left blank."

// Otherwise, if both dates match...


// There is no need to ask the user to justify the date discrepancy, so

// we will hide the text field.

     DateDiscrepancy.presence = "hidden"

// Similarly, this field is no longer mandatory.

     DateDiscrepancy.mandatory = "disabled"

// Voila!


0 Replies