Dot-walking in ServiceNow client scripts allows you to access fields from related records using a dot notation. For example, if you want to access the asset field from the requested_item record in a client script, you can use the getReference method. This method allows you to retrieve records referenced by a field on the form and access their fields.
Here’s a step-by-step example of how you can dot-walk in a client script to check if requested_item.asset equals 'xyz':
Using getReference in an onLoad or onChange Client Script
1. Create a Client Script
Navigate to System Definition > Client Scripts and create a new client script.
2. Select Table and Type
Set the table to the relevant table (e.g., sc_req_item for Requested Item) and the type of the client script (e.g., onChange or onLoad).
3. Write the Client Script
Here's an example for an onChange client script:
function onChange(control, oldValue, newValue, isLoading) {
// Prevent code execution when the form is still loading
if (isLoading || newValue == '') {
return;
}
// Use getReference to retrieve the related record
g_form.getReference('requested_item', function(ritm) {
if (ritm.asset == 'xyz') {
// Your script logic here
g_form.addInfoMessage('Asset is set to xyz.');
// Any other logic you want to execute
}
});
}
For an onLoad client script:
function onLoad() {
// Use getReference to retrieve the related record
g_form.getReference('requested_item', function(ritm) {
if (ritm && ritm.asset == 'xyz') {
// Your script logic here
g_form.addInfoMessage('Asset is set to xyz.');
// Any other logic you want to execute
}
});
}
For an onSubmit client script:
function onSubmit() {
var isValid = true;
// Use getReference to retrieve the related record
g_form.getReference('requested_item', function(ritm) {
if (ritm && ritm.asset == 'xyz') {
// Your script logic here
g_form.addInfoMessage('Asset is set to xyz.');
// Any other logic you want to execute
// Validating the condition (optional)
isValid = false;
}
});
return isValid; // Returns false to prevent form submission if the condition is met
}
Additional Points
g_form.getReference('field_name', callbackFunction) fetches the referenced record asynchronously. The callbackFunction is executed once the referenced record is retrieved.
- Ensure your script logic (e.g., adding an information message) is placed inside the callback function.
- Use checks like
if (ritm) to make sure the referenced record was retrieved before accessing its fields.
- The above examples use the
requested_item field; adjust your field names and logic according to your specific needs.
This approach allows you to dot-walk and access related fields in client scripts, providing a powerful way to interact with complex data structures in ServiceNow forms.