Search code examples
javascriptdynamics-crmmicrosoft-dynamics

D365 CustomJS - Update Field with AutoNumber Field OnSave


I have a Autonumber field called 'ID' that generates an ID for a record. I want to set the Primary Name field called 'ID_Name' to this. I am currently using the following JS:

function setName(executionContext) {

formContext = executionContext.getFormContext();

var name = formContext.getAttribute("id").getValue();
formContext.getAttribute("id_name").setValue(name);

}

Pretty simple. I get the value of 'ID', assign it to a var called name, then set the value of 'ID_Name' to that var. This triggers OnSave.

This works fine when editing a record. The problem is, this does not work when creating a new record. I assume because at the time the OnSave triggers, Autonumber field 'ID' hasn't generated a value which can be used yet, so ID_Name is set to blank. Of course while editing, ID has a value because the record has already been submitted, so no problems. Is there a way around this issue?


Solution

  • Just set the OOB autonumber option on the primary name field of your entity. No code required and it saves you from duplicating data, which should be avoided when possible.