Skip to content
TheChatArchiveThe Chat Archive
gpt-4o-2024-05-13· OpenAIAi2 WildChat-4.8M (AI2)

1 var RitmAssetChecker = Class.create(); 2 RitmAssetChecker.prototype =…

  1. 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

  2. Assistant

    Your code contains several syntax errors and missing elements. Here's the corrected version of your RitmAssetChecker class:

    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:

    1. Define the Class Structure Properly:

      • You have to properly define your class using Class.create() and ensure that the class extends AbstractAjaxProcessor.
    2. Proper Braces and Parenthesis:

      • Ensure that all braces {}, square brackets [], and parenthesis () are properly paired and placed.
    3. Declare Variables Correctly:

      • Ensure variables are declared correctly with var.
    4. Use Proper String Delimiters:

      • Use single quotes ' or double quotes " consistently, and ensure they are paired properly.
    5. Use Proper Parameter Names:

      • Make sure the parameters like 'assetSysId' and 'currentRitmSysId' are correctly used within the this.getParameter() call.
    6. Check for AssetSysId:

      • Ensure that the assetSysId is both checked for null and empty string conditions.
    7. AddEncodedQuery Fix:

      • Correctly fetch and use the relevant query for checking if an asset is already in use.
    8. 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.

  3. 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

  4. 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 Include is 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 Include should interact with the form via a client script, ensure your client script processes the response correctly:

    1. Client Script:
      • Create an onSubmit or onChange client script to call the Script Include.
    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 getXMLAnswer callback in the client script correctly processes the JSON answer.

    4. Test the Script Independently:

    Before wiring everything together, test your Script Include independently 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.

  5. 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;

  6. 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:

    1. Syntax Fixes:

      • Corrected the syntax for g_form.getValue and removed typos.
      • Ensured the correct quotation marks and matching pairs in the string literals.
      • Properly closed the braces {} and parentheses ().
    2. 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.
    3. Error Handling:

      • Added g_form.setSubmit(false) to prevent form submission when an error occurs.
      • Used g_form.showErrorBox instead of g_form.addErrorMessage for inline error display.
    4. Ensuring Form Block Until Ajax Completion:

      • Returning false after initiating GlideAjax to ensure that form submission waits for the async call to complete.

    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.

  7. 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

  8. Assistant

    Let's break down the script again and ensure we catch and handle errors properly and allow the form to submit correctly.

    1. Verify the Script Include is correct and accessible.
    2. Ensure the onSubmit script is properly handling asynchronous Ajax calls.
    3. Make sure the form’s onSubmit behavior 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:

    1. Correct Function Naming and Parameters:

      • Ensure the parameter names (variables.transfer_required and u_asset) match the exact names in your form.
    2. 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.
    3. Adding Safety Checks:

      • Add checks to ensure the form entity values (variables.transfer_required and u_asset) are correctly checked.

    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.
    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 Rules and UI Policies that might interfere with the form submission, especially any client-side validation that might block the operation.
    • 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.

  9. 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

  10. 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 Include is 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

    1. Use of console.log:

      • Added console.log statements to debug and check values at different steps. This helps verify if values are correctly set and retrieved in the browser console.
    2. Try-Catch for JSON Parsing:

      • Wrapped the JSON parsing with a try-catch block to handle any potential errors during parsing.
    3. Handling Both Positive and Negative Cases:

      • Ensure both success and error status responses are properly handled.
    4. Explicit Form Submission:

      • Explicitly call g_form.submit() inside the callback when the form validation is successful.
    5. Debugging in Browser:

      • Open the browser console (F12 or Ctrl+Shift+I for Developer Tools in most browsers) and go to the Console tab to see the output of console.log statements. Track what is being logged to understand where the process might be breaking.

    Additional Testing

    • Network Tab: Check the Network tab 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.