That’s easy!

Clearing a field within Dynamics 365 with some JavaScript is not a big deal. We just call formContext.getAttribute(attributename).setValue(null), save the record, and the job is done.

But unfortunately this is not the case for date only and/or datetime fields. For some reason, when we hit the save button or save the record with formContext.data.entity.save() after clearing these field types via JavaScript, Dynamics just puts the previously known value back in there.

But we really need to clear this field!

Leaving it like this was no option for us as we really needed to clear this field with scripting based on some calculations.

So, after some trial and error I figured out a way how we were able to force the clearance of a date(time) field.

First of all, do not keep the .setValue(null) function. If we keep on using this one, below code will not work.

Instead, we use Xrm.WebApi.updateRecord to update the value directly within the table. Immediately after successfully updating, we refresh the record. Otherwise, when the user would hit the save button or autosave kicks in, the previous value would once again mysteriously appear.

//First get the id for the record to update.
let workOrderId = formContext.data.entity.getId();
if (workOrderId) {
    //Update the record directly in the table
    Xrm.WebApi.updateRecord("msdyn_workorder", workOrderId.replace(/[{}]/gi, ""), {
        msdyn_datewindowend: null
    }).then(function () {
        //Refresh the data on the form
        formContext.data.entity.refresh();
    });
}

As you can see we are using formContext.data.entity.refresh() immediately after updating the record straight into the table. This way users will immediately see that the field actually cleared.

Any other value that has been changed on the form by the user will not be affected either.

So that’s all there is to it!

Happy coding.

 

If you need any help regarding Dynamics 365 customizations and/or configuration, feel free to contact us!