How to set a lookup from JavaScript in a Dynamics 365 form
You can’t set a lookup field by just passing it a GUID. It expects an array containing an object with id, name and entityType, so I usually keep a small helper around to avoid writing it out every time:
function setLookup(executionContext, fieldName, id, name, entityType) {
const formContext = executionContext.getFormContext();
formContext.getAttribute(fieldName).setValue([
{ id: id, name: name, entityType: entityType },
]);
}
// Example: set the parent account
setLookup(executionContext, "parentcustomerid", "00000000-0000-0000-0000-000000000000", "Axazure", "account");entityType takes the logical name of the table (account, contact), not the display name. name is the text shown on the form, and if you leave it out the field looks empty until you save.
Customer lookups such as customerid or parentcustomerid need a bit more care. They accept several tables, and if entityType isn’t the right one the save fails.
To clear the field, use formContext.getAttribute(fieldName).setValue(null).