I would advise to go for a UserEvent script and use the beforeLoad hook instead to set the default values.
/**
* @NApiVersion 2.x
* @NScriptType UserEventScript
*/
define(["N/runtime"], function (runtime) {
function beforeLoad(context) {
var type = context.type
var UserEventType = context.UserEventType;
var newRecord = context.newRecord
if (type != UserEventType.CREATE) return;
var user = runtime.getCurrentUser()
newRecord.setValue({ fieldId: 'subsidiary', value: user.subsidiary });
newRecord.setValue({ fieldId: 'location', value: user.location });
};
return {
beforeLoad: beforeLoad
}
});
If you do want to use the fieldChanged
in the client script and search for the location of the employee, your client script will need permissions on the employee record.
/**
* @NApiVersion 2.x
* @NScriptType ClientScript
*/
define(["N/search"], function (search) {
function fieldChanged(context) {
var currentRecord = context.currentRecord
var fieldId = context.fieldId
if (fieldId != 'entity') return
const id = currentRecord.getValue({ fieldId: fieldId })
if (!id) return
search.lookupFields.promise({
type : search.Type.EMPLOYEE,
id : id,
columns : [ 'subsidiary', 'location' ]
}).then(function(user) {
currentRecord.setValue({ fieldId: 'subsidiary', value: user.subsidiary });
currentRecord.setValue({ fieldId: 'location', value: user.location });
});
}
return {
fieldChanged: fieldChanged
}
});