Dynamics 365 Unified Interface JavaScript to Set a Date Field to Current Date


From recent working with Dynamics 365 customers transitioning to the new Unified Interface – have a CRM Sales User scenario that needs to set a CRM Contact field to the current date on a new record.  The user can then either keep the default current date or set it to another value before saving the new record.

We will need to use JavaScript to set a CRM date field via the Unified Interface or the CRM legacy web client.  The Dynamics 365 Business Rule does not offer a “Current Date” function at this time.  Also Dynamics 365 Workflow or Microsoft Power Automate will not be suitable since it needs the CRM record to be saved in-order to trigger setting a default value (even CRM Workflow running in Real-Time would not work in this case).

So here is the JavaScript – working for both the Unified Interface and CRM legacy web client:

//————–

var Sdk = window.Sdk || {};
(function () {
    this.setFieldCurrentDate = function (executionContext) {
        var formContext = executionContext.getFormContext();
        if(formContext.ui.getFormType()==1) {   // 1 is for new record create state
            var currentDate = new Date();
            formContext.getAttribute(“birthdate”).setValue(currentDate);
        }
    }
}).call(Sdk);

//————–


To setup the above JavaScript:

Add the above JavaScript to a Web Resource

image

 

Add the above Web Resource to the CRM Contact Form Main Library and add “Sdk.setFieldCurrentDate” to the Form Onload event.  Be sure to check on the “Pass execution context as first parameter”.  Publish the CRM Contact entity.

 

image

 

image

 

On a New CRM Contact Record – the Contact’s Birthday field is defaulted to today’s date:

image

 


 

Contact me if you need some Microsoft Dynamics 365 CRM Sales Customer Engagement assistance.

Frank Lee
12 times awarded Microsoft MVP – Dynamics 365 / CRM
San Francisco Bay Area | Silicon Valley

About Microsoft Dynamics 365 / CRM

Microsoft Dynamics 365 CRM/xRM specialist in San Francisco, CA, USA.  Awarded the Microsoft MVP Business Solutions (Dynamics 365/CRM) 12 consecutive times from 2006 to 2018. Actively involved with Microsoft Dynamics CRM implementations since Microsoft CRM v1.0 beta (2002). Super passionate about everything CRM, especially in the areas of Mobile and Cloud Computing, A.I., Digital Transformation, and Business Process Management (BPM).
This entry was posted in Dynamics 365, JavaScript, Unified Interface and tagged , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s