Restricting Date Selection in Dynamics 365 FO using X++
Scenario
Recently, I had a requirement in Dynamics 365 Finance & Operations to restrict the user from entering a transaction date that:
-
Is greater than the current date (future date restriction).
-
Is earlier than 2 days before the current date (past date restriction).
In short:
-
Allowed date range = From 2 days ago to today.
-
Any date outside this range should trigger an error message and reset to today’s date.
Solution Approach
For this requirement, I used the addDays method in X++.
The addDays method allows us to easily calculate a date by adding or subtracting days from a given date.
Syntax:
-
_t: A
utcDateTimevalue representing the starting date and time. -
_value: Number of days to add (positive) or subtract (negative).
Example:
This returns the date & time 2 days before the current date.
Implementation in Form Data Field Event
We can handle the validation when the TransDate field is modified on the form.
Here’s the working X++ code:
[FormDataFieldEventHandler(
formDataFieldStr(InventTransferParmReceive, InventTransferParmTable, TransDate),
FormDataFieldEventType::Modified)]
public static void TransDate_OnModified(FormDataObject sender, FormDataFieldEventArgs e)
{
FormDataSource inventTransferParmReceive_ds = sender.dataSource();
InventTransferParmTable inventTransferParmTable = inventTransferParmReceive_ds.cursor();
// Get current system date
date fixedDate = systemDateGet();
// Convert to UTC dateTime for addDays calculation
utcDateTime fixedUtcDateTime = DateTimeUtil::newDateTime(fixedDate, 0);
// Calculate date range
date fromDate = DateTimeUtil::date(DateTimeUtil::addDays(fixedUtcDateTime, -2)); // 2 days ago
date toDate = fixedDate;
/
if (inventTransferParmTable.TransDate < fromDate || inventTransferParmTable.TransDate > toDate)
{
error("Transaction date must be within the last 2 days and cannot be a future date.");
inventTransferParmTable.TransDate = today(); // Reset to today's date
}
}
Comments
Post a Comment