1 var RitmAssetChecker = Class.create(); 2 RitmAssetChecker.prototype =…
- User
1 var RitmAssetChecker = Class.create(); 2 RitmAssetChecker.prototype = Object.extendsObject(AbstractAjaxProcessor, checkAssetUsage: function() ( var assetSysId this.getParameter(assetSysId'); var currentRitmSysId = this.getParameter("currentRitmSysId'); if (!assetSysId || assetSysId Y 1 return JSON.stringify ( status: error message: 'Asset ID is required H): var ritmGr = new GlideRecord('sc_req_item"); ritmGr.addEncodedQuery('u_asset=' + assetSysId + '^sys_id!-' + ritmGr.query(); if (ritmGr.next()) f return JSON.stringify( status: error message: 'This asset is already used in + ritmGr.number Đ: return JSON.stringify(( status: success message: 'Asset is available for Use
- Assistant
Your code contains several syntax errors and missing elements. Here's the corrected version of your
RitmAssetCheckerclass:var RitmAssetChecker = Class.create(); RitmAssetChecker.prototype = Object.extendsObject(AbstractAjaxProcessor, { checkAssetUsage: function() { var assetSysId = this.getParameter('assetSysId'); var currentRitmSysId = this.getParameter('currentRitmSysId'); if (!assetSysId || assetSysId === '') { return JSON.stringify({ status: 'error', message: 'Asset ID is required' }); } var ritmGr = new GlideRecord('sc_req_item'); ritmGr.addEncodedQuery('u_asset=' + assetSysId + '^sys_id!=' + currentRitmSysId); ritmGr.query(); if (ritmGr.next()) { return JSON.stringify({ status: 'error', message: 'This asset is already used in ' + ritmGr.number }); } return JSON.stringify({ status: 'success', message: 'Asset is available for use' }); } });Here's a breakdown of the changes:
-
Define the Class Structure Properly:
- You have to properly define your class using
Class.create()and ensure that the class extendsAbstractAjaxProcessor.
- You have to properly define your class using
-
Proper Braces and Parenthesis:
- Ensure that all braces
{}, square brackets[], and parenthesis()are properly paired and placed.
- Ensure that all braces
-
Declare Variables Correctly:
- Ensure variables are declared correctly with
var.
- Ensure variables are declared correctly with
-
Use Proper String Delimiters:
- Use single quotes
'or double quotes"consistently, and ensure they are paired properly.
- Use single quotes
-
Use Proper Parameter Names:
- Make sure the parameters like
'assetSysId'and'currentRitmSysId'are correctly used within thethis.getParameter()call.
- Make sure the parameters like
-
Check for AssetSysId:
- Ensure that the
assetSysIdis both checked for null and empty string conditions.
- Ensure that the
-
AddEncodedQuery Fix:
- Correctly fetch and use the relevant query for checking if an asset is already in use.
-
Return JSON Consistently:
- Make sure the error and success messages are returned as valid JSON strings.
By following these corrections, you ensure that the function is well-structured and meets its intended functionality within a ServiceNow environment.
-
- User
This script include is working if the asset is used in another RITM, but if it is not used then i am not able to save the form
- Assistant
If the form is not saving despite the checks functioning as intended, there might be additional factors at play. These could include form validation scripts, UI policies, business rules, or ACLs that could be interfering. However, it's important first to ensure that your
Script Includeis correct and that you handle the response correctly on the client-side if applicable.Here are steps to debug and ensure the proper functioning:
1. Ensure Proper Client-Side Handling:
If your
Script Includeshould interact with the form via a client script, ensure your client script processes the response correctly:- Client Script:
- Create an onSubmit or onChange client script to call the
Script Include.
- Create an onSubmit or onChange client script to call the
function onSubmit() { var ga = new GlideAjax('RitmAssetChecker'); ga.addParam('sysparm_name', 'checkAssetUsage'); // Add the function name from the Script Include ga.addParam('assetSysId', g_form.getValue('u_asset')); // Replace 'u_asset' with the field name in your form ga.addParam('currentRitmSysId', g_form.getUniqueValue()); ga.getXMLAnswer(function(response) { var answer = response.responseXML.documentElement.getAttribute("answer"); var result = JSON.parse(answer); if (result.status === 'error') { g_form.addErrorMessage(result.message); g_form.setSubmit(false); } else { g_form.addInfoMessage(result.message); g_form.setSubmit(true); } }); return false; // Prevent the form from submitting until the Ajax call completes }2. Re-check Script Include Structure:
Verify that the script include is properly defined and accessible:
Script Include:
var RitmAssetChecker = Class.create(); RitmAssetChecker.prototype = Object.extendsObject(AbstractAjaxProcessor, { checkAssetUsage: function() { var assetSysId = this.getParameter('assetSysId'); var currentRitmSysId = this.getParameter('currentRitmSysId'); if (!assetSysId || assetSysId === '') { return JSON.stringify({ status: 'error', message: 'Asset ID is required' }); } var ritmGr = new GlideRecord('sc_req_item'); ritmGr.addEncodedQuery('u_asset=' + assetSysId + '^sys_id!=' + currentRitmSysId); ritmGr.query(); if (ritmGr.next()) { return JSON.stringify({ status: 'error', message: 'This asset is already used in ' + ritmGr.number }); } return JSON.stringify({ status: 'success', message: 'Asset is available for use' }); } });3. Check for Client-Side Syntax:
Make sure your
getXMLAnswercallback in the client script correctly processes the JSONanswer.4. Test the Script Independently:
Before wiring everything together, test your
Script Includeindependently using background scripts to ensure it works as expected. Use the following snippet in background script:var checker = new RitmAssetChecker(); var result = checker.checkAssetUsage(); gs.info(result); // or gs.log(result)5. Examine Browser Console:
Check the browser console for any JavaScript errors that may provide insight into why the form is not saving. Pay attention to network calls and responses for potential clues.
6. Review Form Validations and Business Rules:
Look for any other form validations or business rules that might be preventing the form from saving.
By ensuring the
Script Include, client script, and any potential form validations are correctly configured, you should be able to address and resolve the issue of the form not saving when it is supposed to. - Client Script:
- User
I have this client script. 1 function onSubmit() 2 //Type appropriate comment here, and begin script below 3 var transfer - g_ form.getvalue(variables.transfer_required'); 4 var asset = g form.getValue( u_asset "); 5 if(transfer =='Yes' && asset)( 6 var ga - new GlideAjax( 'RitmAssetChecker '); 7 ga.addParam(`sysparm_name', 'checkAssetUsage'); ga.addParam('assetSysId', asset); ga.addParam('currentRitmSysId', g_form.getUniqueValue()); ga.getXMLAnswer(function(response) var result = JSON.parse(response); if(result.status error') g_form.showErrorBox("asset', result.message); form.addErrorMessage(result.message); g_form.submitted = false; return false; I g_form.submit(); D: return false; return true;
- Assistant
Your client script has a few syntax errors and logical issues. Here's a corrected and improved version:
Corrected Client Script:
function onSubmit() { var transfer = g_form.getValue('variables.transfer_required'); // Ensure correct syntax and case var asset = g_form.getValue('u_asset'); // Ensure correct field name and syntax if (transfer == 'Yes' && asset) { var ga = new GlideAjax('RitmAssetChecker'); ga.addParam('sysparm_name', 'checkAssetUsage'); ga.addParam('assetSysId', asset); ga.addParam('currentRitmSysId', g_form.getUniqueValue()); ga.getXMLAnswer(function(response) { var answer = response.responseXML.documentElement.getAttribute("answer"); var result = JSON.parse(answer); if (result.status == 'error') { g_form.showErrorBox('u_asset', result.message); g_form.addErrorMessage(result.message); g_form.setSubmit(false); return false; } else { g_form.addInfoMessage(result.message); g_form.setSubmit(true); g_form.submit(); // Explicitly submit the form if the asset is available } }); return false; // Prevent the form from submitting until the Ajax call completes } return true; // Allow the form to submit if transfer is not 'Yes' or asset is not defined }Explanation of Changes:
-
Syntax Fixes:
- Corrected the syntax for
g_form.getValueand removed typos. - Ensured the correct quotation marks and matching pairs in the string literals.
- Properly closed the braces
{}and parentheses().
- Corrected the syntax for
-
Properly Handle the GlideAjax Response:
response.responseXML.documentElement.getAttribute("answer")ensures we get the correct response string.- Explicitly call
g_form.submit()if the asset is available after checking the response from the server.
-
Error Handling:
- Added
g_form.setSubmit(false)to prevent form submission when an error occurs. - Used
g_form.showErrorBoxinstead ofg_form.addErrorMessagefor inline error display.
- Added
-
Ensuring Form Block Until Ajax Completion:
- Returning
falseafter initiating GlideAjax to ensure that form submission waits for the async call to complete.
- Returning
Additional Considerations:
- Triggering
onSubmit:- Ensure this client script is set to run onSubmit event for the form.
- You may want to consider async execution and properly managing the flow of asynchronous operations in ServiceNow.
By making these adjustments, your form should be able to save correctly if the asset is not already used in another RITM and should prevent submission with appropriate error messaging if it is.
-
- User
Still not able to save the form if asset is not tagged to another RITM and after these above changes, error message is also not coming
- Assistant
Let's break down the script again and ensure we catch and handle errors properly and allow the form to submit correctly.
- Verify the
Script Includeis correct and accessible. - Ensure the
onSubmitscript is properly handling asynchronous Ajax calls. - Make sure the form’s
onSubmitbehavior is correctly managed.
Here’s an updated version of your client script with detailed comments to ensure everything works as intended:
Updated Client-Side Script:
function onSubmit() { var transfer = g_form.getValue('variables.transfer_required'); var asset = g_form.getValue('u_asset'); // First check if 'transfer' is 'Yes' and 'asset' is populated if (transfer == 'Yes' && asset) { // Create instance of GlideAjax var ga = new GlideAjax('RitmAssetChecker'); ga.addParam('sysparm_name', 'checkAssetUsage'); ga.addParam('assetSysId', asset); ga.addParam('currentRitmSysId', g_form.getUniqueValue()); // Make the asynchronous call ga.getXMLAnswer(function(response) { // Process response var answer = response.responseXML.documentElement.getAttribute("answer"); var result = JSON.parse(answer); if (result.status == 'error') { // Show error message if asset is already in use g_form.showErrorBox('u_asset', result.message); g_form.addErrorMessage(result.message); g_form.setSubmit(false); } else { // Add info message and let the form submission proceed g_form.addInfoMessage(result.message); g_form.setSubmit(true); // This might not be necessary, but it's here for clarity g_form.submit(); // Explicit submit if available } }); return false; // Prevent the form from submitting until the Ajax call completes } return true; // Allow form submission if transfer is not 'Yes' or asset is not defined }Key Points:
-
Correct Function Naming and Parameters:
- Ensure the parameter names (
variables.transfer_requiredandu_asset) match the exact names in your form.
- Ensure the parameter names (
-
Ensuring Asynchronous Call Completion:
- Make sure that
ga.getXMLAnswer's callback processes the response correctly. - Set
g_form.setSubmit(false)when an error occurs to prevent form submission. - Explicitly call
g_form.submit()inside the callback when the form is good to go.
- Make sure that
-
Adding Safety Checks:
- Add checks to ensure the form entity values (
variables.transfer_requiredandu_asset) are correctly checked.
- Add checks to ensure the form entity values (
Debugging Steps:
- Console Log Statements:
- Add
console.log()statements to debug and check values at different steps in your client script to ensure they're being set and retrieved correctly.
- Add
console.log('Transfer Required:', transfer); console.log('Asset:', asset); console.log('Response Received:', answer); console.log('Parsed Result:', result);-
Check Business Rule and UI Policies:
- Review any
Business RulesandUI Policiesthat might interfere with the form submission, especially any client-side validation that might block the operation.
- Review any
-
Check Network Activity:
- Use browser developer tools (Network tab) to ensure the GlideAjax call is being made and is returning the correct data.
Modified Server-Side Script: (Optional, for clarity)
var RitmAssetChecker = Class.create(); RitmAssetChecker.prototype = Object.extendsObject(AbstractAjaxProcessor, { checkAssetUsage: function() { var assetSysId = this.getParameter('assetSysId'); var currentRitmSysId = this.getParameter('currentRitmSysId'); if (!assetSysId || assetSysId === '') { return JSON.stringify({ status: 'error', message: 'Asset ID is required' }); } var ritmGr = new GlideRecord('sc_req_item'); ritmGr.addEncodedQuery('u_asset=' + assetSysId + '^sys_id!=' + currentRitmSysId); ritmGr.query(); if (ritmGr.next()) { return JSON.stringify({ status: 'error', message: 'This asset is already used in ' + ritmGr.number }); } return JSON.stringify({ status: 'success', message: 'Asset is available for use' }); } });Testing in Background Script:
var checker = new RitmAssetChecker(); checker.setParameter('assetSysId', 'Asset-Id-Here'); // Replace with actual Asset Sys ID checker.setParameter('currentRitmSysId', 'Current-RITM-ID-Here'); // Replace with current RITM Sys ID var result = checker.checkAssetUsage(); gs.info(result); // or gs.log(result)With these changes and debugging steps, you should be able to save the form properly and handle errors effectively.
- Verify the
- User
First script inculde and the client script that i provide is working if the asset is used in another ritm but not working if asset is not used. Please modify those
- Assistant
I understand the issue now. The core problem might be with how the response is handled when the asset is not used in another RITM. Let's fine-tune the scripts to ensure both positive and negative checks are properly handled.
Script Include
Ensure your
Script Includeis correctly structured to return appropriate responses. Here's a refined version:var RitmAssetChecker = Class.create(); RitmAssetChecker.prototype = Object.extendsObject(AbstractAjaxProcessor, { checkAssetUsage: function() { var assetSysId = this.getParameter('assetSysId'); var currentRitmSysId = this.getParameter('currentRitmSysId'); if (!assetSysId || assetSysId === '') { return JSON.stringify({ status: 'error', message: 'Asset ID is required' }); } var ritmGr = new GlideRecord('sc_req_item'); ritmGr.addEncodedQuery('u_asset=' + assetSysId + '^sys_id!=' + currentRitmSysId); ritmGr.query(); if (ritmGr.next()) { return JSON.stringify({ status: 'error', message: 'This asset is already used in ' + ritmGr.number }); } return JSON.stringify({ status: 'success', message: 'Asset is available for use' }); } });Client Script
Now, let's refine your client script to ensure it properly handles both cases and debug issues if the form is not being saved. Here's the modified and detailed client script:
function onSubmit() { var transfer = g_form.getValue('variables.transfer_required'); var asset = g_form.getValue('u_asset'); console.log('Transfer Required:', transfer); console.log('Asset:', asset); // First check if 'transfer' is 'Yes' and 'asset' is populated if (transfer == 'Yes' && asset) { // Create instance of GlideAjax var ga = new GlideAjax('RitmAssetChecker'); ga.addParam('sysparm_name', 'checkAssetUsage'); ga.addParam('assetSysId', asset); ga.addParam('currentRitmSysId', g_form.getUniqueValue()); // Make the asynchronous call ga.getXMLAnswer(function(response) { // Read the `answer` attribute from response XML var answer = response.responseXML.documentElement.getAttribute("answer"); // Ensure we have valid JSON string console.log('Response Received:', answer); try { // Parse the JSON string var result = JSON.parse(answer); console.log('Parsed Result:', result); // Check if status is 'error' and handle accordingly if (result.status == 'error') { g_form.showErrorBox('u_asset', result.message); g_form.addErrorMessage(result.message); g_form.setSubmit(false); } else { // If success, allow form submission g_form.addInfoMessage(result.message); g_form.setSubmit(true); g_form.submit(); // Explicit submit if available } } catch (e) { console.error('Error parsing response:', e); g_form.addErrorMessage('There was an error processing the response from the server.'); g_form.setSubmit(false); } }); return false; // Prevent the form from submitting until the Ajax call completes } return true; // Allow form submission if transfer is not 'Yes' or asset is not defined }Key Improvements
-
Use of
console.log:- Added
console.logstatements to debug and check values at different steps. This helps verify if values are correctly set and retrieved in the browser console.
- Added
-
Try-Catch for JSON Parsing:
- Wrapped the JSON parsing with a
try-catchblock to handle any potential errors during parsing.
- Wrapped the JSON parsing with a
-
Handling Both Positive and Negative Cases:
- Ensure both
successanderrorstatus responses are properly handled.
- Ensure both
-
Explicit Form Submission:
- Explicitly call
g_form.submit()inside the callback when the form validation is successful.
- Explicitly call
-
Debugging in Browser:
- Open the browser console (
F12orCtrl+Shift+Ifor Developer Tools in most browsers) and go to theConsoletab to see the output ofconsole.logstatements. Track what is being logged to understand where the process might be breaking.
- Open the browser console (
Additional Testing
- Network Tab: Check the
Networktab in the browser's developer console to ensure the GlideAjax call is being made and the response is properly returned. - Form Validation: Ensure there are no other scripts or policies interfering with the form submission.
With these improvements, the script should properly handle both scenarios—when the asset is used and when it’s not used—in another RITM, ensuring the correct behavior during form submission.
-