Prefill a Date Field with Today’s Date in Dynamics CRM 2011

Paul Nieuwelaar, 08 July 2011

A common issue for users of any system has to input the same dates over multiple records. For example when creating new Invoices in Dynamics CRM 2011 you will often set the Date Delivered field to Today’s date by default, so why not automate this? To make this whole process a bit smoother we can add some JScript to the Invoice to prefill the Date Delivered to today’s date. This means that when we create a new Invoice, we don’t have to worry about setting the Date Delivered manually each time; however we can still overwrite this.

 Prefill a Date Field with Today’s Date in Dynamics CRM 2011

In my last post I had explained some other methods for Prefilling Fields in Dynamics CRM 2011, which contained a function that worked on most field types. Setting the current day in date fields using that function did not work, so I have created another function that is mostly the same, but will work for with date fields.

To set up this function to be used on any date field, you will need to Create a new Web Resource to hold the JScript. This JScript Library should contain the following code:

// Prefill a Date Field with Todays Date  
function setToday(date) {
    var isCreateForm = Xrm.Page.ui.getFormType() == 1;
    var dateField = Xrm.Page.getAttribute(date);
    if (isCreateForm) { // Check that this is a new Record
        dateField.setValue(new Date()); // Set the Date field to Today
        dateField.setSubmitMode("always"); // Save Disabled Fields
    }
}

Once this Web Resource is created, you need to add the JScript Library to the form properties of the Invoice for example, and then create a new Event Handler for the OnLoad event to call this function. We will also need to enter the date field we are prefilling into the parameters area, which should look something like the image below:

 Prefill a Date Field with Today’s Date in Dynamics CRM 2011

Finally we can preview our form, and see that the Date Delivered field of the Invoice is being prefilled to today’s date when we create a new record. Because we set the date field with each Event Handler we add, we can reuse this function on any field of any entity to prefill a date field with today’s date.

 Prefill a Date Field with Today’s Date in Dynamics CRM 2011