Sometimes I get a requirement to set the initial value for a DateTime field, such as the Due Date of the Task Entity, to Today’s date. OR, someone would like to set the hour of a DateTime field to something other than Midnight, which is the default.
JavaScript to the rescue:
Add this function to the web resource that contains the JavaScript for your entity:
function SetDefaultDateTimeValue(attributeName, hour, minute) { // FORM_TYPE_CREATE = 1 if (Xrm.Page.ui.getFormType() == 1) { var attribute = Xrm.Page.getAttribute(attributeName); if (attribute.getValue() == null) { attribute.setValue(new Date()); } attribute.setValue(attribute.getValue().setHours(hour, minute, 0)); } }
Make the form’s OnLoad function, look something like this:
function Form_OnLoad() { SetDefaultDateTimeValue('scheduledend', 8, 0); }
Results
The results of this operation look like this:
SetDefaultDateTimeValue Function
The function I created takes three parameters:
attributeName | Name of the DateTime attribute you wish to set |
hour | The hour of the day to set ( can be zero ) |
minute | The minute of hour to set ( can be zero ) |
You would call this function once for each of the form fields that you wish to set. Just change the parameters passed as necessary.
Other Notes
You will notice that I am checking the Form Type before performing any work. A form type of 1 is a Create Form which is the form type for a New record within CRM. We put this check in place so that we only populate our fields for new records. The fields of existing records will remain unchanged when opened.
This is how the Form Events look after having wired up a JScript web resource and specifying the OnLoad event: