Hi, I have created a blank option set and using it on a form in a model driven app. Using JS I am dynamically adding all available Security roles as options. Also when saving the form, I reset the value to empty as it doesn't allow me to save a value which does not exist on the option set. To solve this I have another text field, hidden on the form where I save the roleId.
To load the selected role value on an existing record, i am trying to set the value of this dynamics option set to the role that was saved on the hidden field. This is for some reason doesn't allow me to. Please suggest if there is an alternate for this.
// Form load event
this.onFormLoaded = async function(executionContext) {
this.formContext = executionContext.getFormContext();
await Xrm.WebApi.retrieveMultipleRecords('role').then(this.onRolesFetchCallback, this.errorCallbackor);
let selectedRole = this.formContext.getControl('new_selectedrole').getAttribute().getValue();
roles.forEach((role, index) => {
this.formContext.getControl('new_roleoptions').addOption({text: role.name, value: index})
});
if(selectedRole) {
let role = roles.find(role => role.roleid === selectedRole)
if(role) {
this.formContext.getControl('new_roleoptions').getAttribute().setValue(roles.indexOf(role));
}
}
}
// Callback when all the security roles are fetched
this.onRolesFetchCallback = function(result) {
roles = result.entities;
}
// Set the selected role from dynamic role options to the hidden selectedRole text field
this.onRoleSelected = function(executionContext) {
let selectedRole = this.formContext.getControl('new_roleoptions').getAttribute().getValue();
console.log(roles[selectedRole].roleid)
this.formContext.getControl('new_selectedrole').getAttribute().setValue(roles[selectedRole].roleid);
}
Note - I am using Dynamics 365 and CDS instance. Also, I cannot use lookup field for Security Roles as it is turns up as a readonly field on the form which we cannot change.
Thanks