Blog

Forms - How to set the value of a field to todays date for new records only

A common requirement is to set the default value of a form field to today's date, only when a user enters a new record. In edit mode, the field value should remain the same. This post walks through how to carry out this task.

Setting default form values is a topic that I've covered in the previous post beneath.


However, I've recently seen several questions from users that specifically ask how to set the date and time on new records only, and to not update the value on an update. Therefore, this post covers this exact requirement.

Creating an example SharePoint list/Data source

Let's take the example of the following SharePoint list. This list stores property details and includes a field called 'acquisition date'. The requirement is to set this field to today's date when a user creates a new record. When a user updates a record, it should retain this initial value.


Defaulting a form field to today's date when adding a new record

To demonstrate how to set the "acquisition date" to today's date when a user creates a new record, we'll start by creating an auto-generated app that's based on the above SharePoint list.

On the edit form, we unlock the "acquisition date" card, and we set the Default property to the following:

If(EditForm1.Mode=FormMode.New, 
Now(),
ThisItem.AquisitionDate
)


The typical mistake that novice app builders make is to set the default property to Now() and omit the conditional statement that detects the form mode. This causes the form field to display today's date when editing a record (which is not the correct behaviour).

When we now run our app, the acquisition date field will now default to today's date when the user adds a new record.

Making a field read-only in edit mode only

The natural requirement that often follows is to make the acquisition date field read-only when editing a record.

To implement this requirement, we set the DisplayMode property to the following:

If(EditForm1.Mode=FormMode.New, 
DisplayMode.Edit,
DisplayMode.View
)


When a user now edits an existing record, the 'acquisition date' card will be set to "display mode view", and will not allow the user to update the value.

Conclusion

When building data entry forms, a common requirement is to set default a field to today's date when adding a new record only. This post waked through how to carry out this task.