Unable to get the User details on widget based on user selection

Rama26
Tera Contributor

HI,

 

I have a variable on catalog item User. it's reference based on user selection i need to display few fields using widget but it's not working

Html:

<div class="container p-3">
<div class="bg-light p-3 rounded" ng-if="c.userInfo">
<div><strong>Name:</strong> {{ c.userInfo.name || 'N/A' }}</div>
<div><strong>Sys ID:</strong> {{ c.userInfo.sys_id || 'N/A' }}</div>
</div>
</div>

Client Script

function($scope, spUtil) {
var c = this;

// Assuming 'user_details' is your variable holding sys_id
var selectedSysId = $scope.page.g_form.getValue('user_details');

if (selectedSysId) {
c.server.get({ selected_user_sysid: selectedSysId }).then(function(response) {
c.userInfo = response.userInfo;
});
}
}

Server Side

(function() {
data.userInfo = null;

// Check if the variable is present
if (input && input.selected_user_sysid) {
var gr = new GlideRecord('sys_user');
if (gr.get(input.selected_user_sysid)) {
data.userInfo = {
name: gr.name + '',
sys_id: gr.getUniqueValue() + ''
};
}
}
})();.   can any one help me on this?

1 REPLY 1

pavani_paluri
Giga Guru

Hi @Rama26 

 

I see why your widget isn’t updating — the way you’re grabbing the catalog variable value won’t work as you expect in Service Portal because g_form.getValue() in the client controller only returns a value once at load. It won’t automatically react to changes, and in a Catalog Item widget you need to explicitly listen for variable changes using $scope.$on() or the g_form.$private.events API.
Timing of g_form.getValue()
When your widget loads, if the user hasn’t yet picked a user in the user_details variable, getValue() will return "".
You need to listen for when the reference field changes.
In Catalog Item widgets, g_form.getValue() uses the question name (variable name), not the label.
If your variable is named user_details, make sure you use exactly that.
After the user picks a new value, you should call c.server.get() again to refresh the displayed details.

Updted client script:
function($scope, spUtil) {
var c = this;

function fetchUserInfo(sysId) {
if (sysId) {
c.server.get({ selected_user_sysid: sysId }).then(function(response) {
c.userInfo = response.userInfo;
});
} else {
c.userInfo = null;
}
}

// Initial load
fetchUserInfo($scope.page.g_form.getValue('user_details'));

// Listen for changes to the variable
$scope.$on('spModel.gForm.field.change', function(evt, parms) {
if (parms.field.name === 'user_details') {
fetchUserInfo(parms.newValue);
}
});
}