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

In servicenow, i have a ritm and there is a reference field in the ritm called asset,…

  1. User

    In servicenow, i have a ritm and there is a reference field in the ritm called asset, and refer to the harware table. My requirement is if anyone select the asset in this field and then try to save the form, it will check if the ritm variable named transfer is yes. Then it will check for the other items in which this asset is already selected. If yes then prevent the form to submit and show error message with the ritm name in which it is already selected.

  2. Assistant

    To achieve your requirement in ServiceNow, you can implement a client-side script, specifically a "onSubmit" Client Script on the RITM form. This script will check the value of the transfer variable, validate if the selected asset is already being used in another RITM, and then either allow or prevent the form submission based on the condition.

    Here is a step-by-step guide along with the example code for the Client Script:

    1. Navigate to Client Scripts:

      • Go to System Definition > Client Scripts.
    2. Create a New Client Script:

      • Click on New to create a new Client Script.
      • Fill in the necessary fields:
        • Name: "Prevent duplicate assets on transfer"
        • Table: sc_req_item (Assuming it's the RITM table)
        • Type: onSubmit
    3. Add the Client Script logic:

      (function executeRule(current, g_form, g_user, g_scratchpad) {
          // The GlideRecord to check for RITM items with the same asset
          var assetSelected = g_form.getReference('asset');
          var transferVariable = g_form.getValue('transfer');
          
          // Continue only if the transfer variable is yes
          if (transferVariable === 'yes' && assetSelected) {
              var otherRITM = new GlideRecord('sc_req_item');
              otherRITM.addQuery('asset', assetSelected.sys_id); // Adjust the query to match the field names
              otherRITM.addQuery('sys_id', '!=', current.sys_id); // Exclude the current RITM
              otherRITM.query();
              
              if (otherRITM.next()) {
                  var warningMessage = 'This Asset is already selected in RITM: ' + otherRITM.number;
                  g_form.addErrorMessage(warningMessage);
                  return false; // Prevent form submission
              }
          }
          
          return true; // Allow form submission if no duplicate is found
      })(current, g_form, g_user, g_scratchpad);
      
    4. Save the Client Script:

      • Once the script is in place, save it.

    Explanation of the script:

    • The script first checks if the transfer variable is set to 'yes' and if an asset is selected.
    • If those conditions are met, it creates a GlideRecord query on the sc_req_item table to find any other RITM records with the same asset selected, excluding the current RITM.
    • If a duplicate is found, an error message is displayed with the RITM number in which the asset is already selected, and the form submission is prevented.
    • If no duplicate is found, the form submission proceeds as usual.

    This should achieve your requirement of preventing the submission of a RITM if the selected asset is already in use in another RITM, and displaying an appropriate error message.

  3. User

    We cannot use glide record in client scripts

  4. Assistant

    You're right. My apologies for the oversight. Since GlideRecord can't be used in client scripts, we will have to leverage a GlideAjax call to accomplish this. GlideAjax allows the client script to call a server-side script include, which can perform the database operations (e.g., querying for existing RITMs with the same asset).

    Here's how you can achieve this with GlideAjax:

    Step 1: Create a Script Include

    1. Navigate to Script Includes:

      • Go to System Definition > Script Includes.
    2. Create a New Script Include:

      • Click New to create a new Script Include.
      • Fill in the necessary fields:
        • Name: RITMAssetChecker
        • Client Callable: true
        • Accessible from: All Application Scopes (or specific scope as needed)
    3. Add the following code to the Script Include:

      var RITMAssetChecker = Class.create();
      RITMAssetChecker.prototype = Object.extendsObject(AbstractAjaxProcessor, {
          checkAssetUsage: function(assetSysId, currentRitmSysId) {
              var gr = new GlideRecord('sc_req_item');
              gr.addQuery('asset', assetSysId);
              gr.addQuery('sys_id', '!=', currentRitmSysId); // Exclude the current RITM
              gr.query();
              
              if (gr.next()) {
                  return gr.number; // Returns the RITM number with the duplicate asset
              }
              return ''; // No duplicate found
          }
      });
      

    Step 2: Create a Client Script

    1. Navigate to Client Scripts:

      • Go to System Definition > Client Scripts.
    2. Create a New Client Script:

      • Click on New to create a new Client Script.
      • Fill in the necessary fields:
        • Name: Prevent duplicate assets on transfer
        • Table: sc_req_item (or appropriate table)
        • Type: onSubmit
    3. Add the following code to the Client Script:

      function onSubmit() {
          var transfer = g_form.getValue('transfer');
          var assetId = g_form.getValue('asset');
          var currentRitmId = g_form.getUniqueValue();
      
          // Check if the transfer variable is 'yes'
          if (transfer === 'yes' && assetId) {
              var ga = new GlideAjax('RITMAssetChecker');
              ga.addParam('sysparm_name', 'checkAssetUsage');
              ga.addParam('assetSysId', assetId);
              ga.addParam('currentRitmSysId', currentRitmId);
              ga.getXMLAnswer(function(response) {
                  var ritmNumber = response.responseXML.documentElement.getAttribute("answer");
                  if (ritmNumber) {
                      var warningMessage = 'This Asset is already selected in RITM: ' + ritmNumber;
                      g_form.addErrorMessage(warningMessage);
                      g_form.submitted = false;
                  } else {
                      g_form.submit();
                  }
              });
              return false;  // Prevent the form from submitting until the response is received
          }
          return true;  // Allow the form to be submitted if transfer is not 'yes' or asset is not selected
      }
      

    Explanation of the Client Script:

    • The onSubmit function checks if the transfer variable is 'yes' and if an asset is selected.
    • If the conditions are met, a GlideAjax call is made to the Script Include RITMAssetChecker.
    • The Script Include's checkAssetUsage function searches for other RITM records with the same asset, excluding the current RITM.
    • The server-side function returns the RITM number if a duplicate is found.
    • The client script then displays an error message if a duplicate is found and prevents the form from submitting. If no duplicate is found, the form submission is allowed.

    These steps should meet your requirement to prevent form submission and notify the user if the selected asset is already used in another RITM with the transfer variable set to 'yes'.

  5. User

    I am not able to save the form, for transfer variables. Logic is working if asset is found in another ritm. But if not found, in this case i cannot able to save the form

  6. Assistant

    It sounds like there's an issue with the asynchronous nature of the GlideAjax call, which can sometimes cause form submission problems if not handled correctly. In the provided Client Script, the form's submission should be explicitly triggered after the GlideAjax call completes if no duplicate asset is found.

    To ensure the form can be saved correctly when no duplicate asset is found, we can implement the GlideAjax call synchronously or manage the form submission in the callback more explicitly.

    Here is an adjusted version of the Client Script which ensures the form submits correctly in both cases:

    Adjusted Client Script:

    1. Navigate to Client Scripts:

      • Go to System Definition > Client Scripts.
    2. Open the Existing Client Script or Create a New One:

      • Open your previously created client script for modification or create a new one if you haven’t created it yet.
    3. Modify the Client Script logic:

      function onSubmit() {
          var transfer = g_form.getValue('transfer');
          var assetId = g_form.getValue('asset');
          var currentRitmId = g_form.getUniqueValue();
      
          if (transfer === 'yes' && assetId) {
              // Create a deferred object to manage the asynchronous GlideAjax call
              var ga = new GlideAjax('RITMAssetChecker');
              ga.addParam('sysparm_name', 'checkAssetUsage');
              ga.addParam('assetSysId', assetId);
              ga.addParam('currentRitmSysId', currentRitmId);
      
              // We need to add this logic inside a Promise to handle the async call efficiently
              return new Promise(function (resolve, reject) {
                  ga.getXMLAnswer(function(response) {
                      var ritmNumber = response.responseXML.documentElement.getAttribute("answer");
                      if (ritmNumber) {
                          var warningMessage = 'This Asset is already selected in RITM: ' + ritmNumber;
                          g_form.addErrorMessage(warningMessage);
                          reject(); // Form submission should not proceed
                      } else {
                          resolve(); // Form submission can proceed
                      }
                  });
              }).then(function () {
                  return true; // Allow form submission
              }).catch(function () {
                  return false; // Prevent form submission
              });
          }
          return true;  // Allow form submission if transfer is not 'yes' or asset is not selected
      }
      

    Explanation:

    • Promise Handling: The change involves using JavaScript Promises to handle the async nature of the GlideAjax call.
      • When the form submits, the onSubmit function creates a new Promise.
      • Inside the Promise, the GlideAjax call is used to perform the asset check.
      • resolve() is called if no duplicate RITM is found, allowing the form to submit.
      • reject() is called if a duplicate RITM is found, preventing the form from submitting.
    • Return Statements: The return statements are embedded within the .then and .catch blocks to ensure correct logic flow.

    This should ensure the form handles both the cases where the asset is found in another RITM and where the asset is not found, allowing the form to be saved correctly when appropriate.

  7. User

    Error is showing but form is submit

  8. Assistant

    To ensure that the form submission is properly prevented when a duplicate asset is found, you need to manage the asynchronous behavior properly and explicitly control the form submission flow. Here is a refined approach to handle this:

    Adjusted Client Script:

    1. Navigate to Client Scripts:

      • Go to System Definition > Client Scripts.
    2. Open the Existing Client Script or Create a New One:

      • Open your previously created client script for modification or create a new one if you haven’t created it yet.
    3. Modify the Client Script logic:

      function onSubmit() {
          var transfer = g_form.getValue('transfer');
          var assetId = g_form.getValue('asset');
          var currentRitmId = g_form.getUniqueValue();
      
          if (transfer === 'yes' && assetId) {
              var ga = new GlideAjax('RITMAssetChecker');
              ga.addParam('sysparm_name', 'checkAssetUsage');
              ga.addParam('assetSysId', assetId);
              ga.addParam('currentRitmSysId', currentRitmId);
      
              // Use a synchronous GlideAjax call by processing the result within the getXMLWait() method
              var response = ga.getXMLWait();
              var ritmNumber = response.documentElement.getAttribute("answer");
              if (ritmNumber) {
                  var warningMessage = 'This Asset is already selected in RITM: ' + ritmNumber;
                  g_form.addErrorMessage(warningMessage);
                  return false; // Prevent form submission
              }
          }
          return true;  // Allow form submission if transfer is not 'yes' or asset is not selected
      }
      

    Explanation:

    1. Synchronous GlideAjax Call:

      • Using the getXMLWait() method from GlideAjax instead of the asynchronous getXMLAnswer() ensures that the code waits for the server response before proceeding.
      • This synchronous call fetches the response and processes it immediately, which simplifies control over the form submission flow.
    2. Immediate Decision Based on Response:

      • If a duplicate RITM (ritmNumber) is found, an error message is displayed, and return false prevents the form submission.
      • If no duplicate is found, the form submission proceeds as intended with return true.

    This solution should address the issue by strictly controlling the form submission logic synchronously and ensuring that the form is not submitted when a duplicate asset is found.

  9. User

    Not working with client script and script include. If asset found in another ritm then it is working and prevent form submission but also if not working still error is not showing but form is also not submitted

  10. Assistant

    If using synchronous GlideAjax isn't resolving the issue and asynchronous logic is causing problems with form submission, another approach is to use the g_scratchpad object within a Business Rule and combine it with your Client Script. This ensures a server-side check is done before form submission and maintains form control on the client-side.

    Here is how you can achieve that:

    Step 1: Create a Business Rule

    1. Navigate to Business Rules:

      • Go to System Definition > Business Rules.
    2. Create a New Business Rule:

      • Click New to create a new Business Rule.
      • Fill in the necessary fields:
        • Name: Check Duplicate Asset on Transfer
        • Table: sc_req_item (or the appropriate RITM table)
        • Active: true
        • When: before
        • Insert: true
        • Update: true
    3. Add Condition and Script:

      • In the Advanced section, check the Use advanced condition box, and write a condition similar to:
        current.variables.transfer == 'yes' && !gs.nil(current.variables.asset);
        
      • Add the following script to perform the asset validation:
        (function executeRule(current, previous /*null when async*/) {
            var assetSelected = current.variables.asset;
            if (assetSelected) {
                var otherRITM = new GlideRecord('sc_req_item');
                otherRITM.addQuery('variables.asset', assetSelected.toString()); // Adjust the query to match field names
                otherRITM.addQuery('sys_id', '!=', current.sys_id); // Exclude the current RITM
                otherRITM.query();
                
                if (otherRITM.next()) {
                    gs.addErrorMessage('This Asset is already selected in RITM: ' + otherRITM.number);
                    current.setAbortAction(true);  // Prevent the record save/submit
                }
            }
        })(current, previous);
        

    Step 2: Optional (to add Client-side Error Message display)

    Since the Business Rule already prevents the form submission and adds a server-side error message, adding a Client Script for error display is optional:

    1. Navigate to Client Scripts:

      • Go to System Definition > Client Scripts.
    2. Create a New Client Script:

      • Click on New to create a new Client Script.
      • Fill in the necessary fields:
        • Name: Show Error Messages
        • Table: sc_req_item
        • Type: onLoad
    3. Add the following code to the Client Script logic:

      function onLoad() {
          var errorMessage = g_form.getErrorMessages();
          if (errorMessage) {
              g_form.addErrorMessage(errorMessage);
          }
      }
      

    Explanation:

    1. Business Rule:

      • The Business Rule runs before the record is inserted or updated.
      • It checks if the transfer variable is 'yes' and if an asset is selected.
      • It then queries the sc_req_item table for other records with the same asset, excluding the current RITM.
      • If a record with the same asset is found, an error message is added, and the record save/submit is aborted using current.setAbortAction(true).
    2. Optional Client Script:

      • The Client Script ensures that any error message from the server is displayed on the form.

    Using this approach leverages server-side logic to ensure correctness and prevents form submission, while also optionally enhancing the user experience by ensuring error messages are clearly displayed on the client side. This should prevent the form from submitting if there's a conflict and display the necessary error messages effectively.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.