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:

  1. Is greater than the current date (future date restriction).

  2. 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:

addDays(_t, _value)
  • _t: A utcDateTime value representing the starting date and time.

  • _value: Number of days to add (positive) or subtract (negative).

Example:

DateTimeUtil::addDays(DateTimeUtil::utcNow(), -2);

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

Popular posts from this blog

JSON-Based HTTP POST Request from X++ to Retrieve an Access Token

Calling an External API from D365FO Using X++ to Retrieve a Token