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

in servicenow, i have a multiline string variable field and one more reference field…

  1. User

    in servicenow, i have a multiline string variable field and one more reference field refer to the cmdb_ci_server table, my requirement is if we select any server in the reference field and after selecting the server if multiline string variable field is empty then we need to populate the sys_class_name field display value of the selected server in the string field named server_result presented on the form

  2. Assistant

    In ServiceNow, to achieve the desired functionality where selecting a server from a reference field populates a multiline string variable with the sys_class_name of the selected server when that multiline field is empty, you can use a client script. Here’s a step-by-step guide on how you can implement this:

    Steps to Implement the Script:

    1. Create a Client Script:

      • Navigate to System Definition > Client Scripts in your instance.
    2. Configure the Client Script:

      • Name: Provide an appropriate name for the client script.
      • Table: Select the table where this script should run.
      • Type: Choose onChange as the type since you want this to execute when the reference field changes.
      • Field name: Select your reference field that refers to cmdb_ci_server.
      • Active: Ensure this is checked to make the script active.
      • Global: You can check this if you want the script to be reusable.
    3. Write the Script: Here’s a sample script that populates the multiline string field when the server reference field changes:

      function onChange(control, oldValue, newValue, isLoading) {
          if (isLoading || newValue === '') {
              return;
          }
      
          // Reference to the server field value
          var serverReference = g_form.getReference('your_reference_field_name', function(server) {
              // Check if multiline string variable field is empty
              if (g_form.getValue('your_multiline_string_field') === '') {
                  // Set the multiline string field value with the sys_class_name display value
                  g_form.setValue('your_multiline_string_field', server.sys_class_name.getDisplayValue());
              }
          });
      }
      
      • Replace your_reference_field_name with the actual name of your reference field.
      • Replace your_multiline_string_field with the name of your multiline string variable field.

    Additional Notes:

    • Asynchronous Callback: The use of g_form.getReference() is asynchronous, which is why it takes a callback function. This ensures that the field is populated once the reference data is retrieved.
    • Conditions: Make sure you check if your multiline field is initially empty before setting its value. This prevents overwriting any user input.

    Testing the Script:

    • Test your implementation in a development or test instance first to ensure it behaves as expected.
    • You can add additional logging or alerts to debug if necessary, for instance using gs.addInfoMessage() or console.log() for debugging.

    This approach should meet your requirements, populating the relevant field dynamically based on the selected server in the reference field.

  3. User

    how to take the sys_class_name display value to string field without script include

  4. Assistant

    To populate a string field with the sys_class_name display value from a reference field in ServiceNow without using a Script Include, you can achieve this directly within a client-side script like a client script or a business rule (though client-side action is more appropriate for immediate UI updates). Here's how you can do it using a Client Script:

    Using a Client Script

    The Client Script approach is suitable for updating fields on the form while a user is interacting with it. Here's what you need to do:

    1. Create a New Client Script:

      • Navigate to System Definition > Client Scripts.
      • Click on New.
    2. Configure the Client Script:

      • Name: Enter a descriptive name for the script.
      • Table: Specify the table that contains your reference and target string fields.
      • Type: Set it to onChange.
      • Field name: Set the field name to the reference field that points to cmdb_ci_server.
      • Active: Ensure this option is checked.
    3. Script Logic: Write the following script in the Script field:

      function onChange(control, oldValue, newValue, isLoading) {
          if (isLoading || newValue === '') {
              return;
          }
      
          // Use getReference to fetch the full record of the selected server
          g_form.getReference('your_reference_field_name', function(server) {
              // Check if the multiline string field is empty and set the sys_class_name
              if (g_form.getValue('your_multiline_string_field') === '') {
                  var sysClassNameDisplay = server.sys_class_name.getDisplayValue();
                  g_form.setValue('your_multiline_string_field', sysClassNameDisplay);
              }
          });
      }
      
      • Replace your_reference_field_name with the actual name of your reference field pointing to the cmdb_ci_server.
      • Replace your_multiline_string_field with the actual name of your multiline string field that you want to populate.

    Explanation

    • OnChange Script: This script runs whenever the value of your reference field changes.
    • getReference(): This function fetches the complete server record from the database. It's asynchronous, meaning the callback function provided to getReference() executes once the server data is available.
    • g_form.setValue(): Sets the value of the multiline string field if it is currently empty.

    Points to Consider

    • This solution assumes that the sys_class_name field exists in the referenced table (in this case, it should be part of the configuration item fields), and it has a display value that you want to use.
    • Test this client script in a DEV/TEST environment to ensure it works correctly with your form setup.
    • If the sys_class_name does not have a meaningful display value or is not accessible as described, you might have to adjust based on your available fields or rethink the logic depending on how sys_class_name has been configured on your instances.

    This approach provides you with a dynamic way to populate a form field based on a user's interactions with the reference field, providing real-time feedback and updates.

  5. User

    not working , multiline field is populated based on selected server, if after selecting the server it is empty then we need to populate the string field named server_result with the sys_class_name of the selected server

  6. Assistant

    To achieve the functionality where, upon selecting a server from a reference field, the server_result string field is populated with the sys_class_name of the selected server if the multiline field is empty, you can use a client script in ServiceNow. Here's how to set it up:

    Creating a Client Script

    1. Navigate to: System Definition > Client Scripts.

    2. Click on: New to create a new client script.

    3. Fill in the Client Script details:

      • Name: Enter a name for your script, like “Populate Server Result”.
      • Table: Select the table where your fields are located.
      • Type: Choose onChange.
      • Field name: Specify the name of your reference field (e.g., server_reference_field).
      • Active: Make sure this is checked.
      • Global: You can check this if you intend it to be global; otherwise, leave unchecked if specific to the current table.
    4. Script Logic: Write the following script in the Script field:

      function onChange(control, oldValue, newValue, isLoading) {
          if (isLoading || newValue === '') {
              return;
          }
      
          // Use getReference to fetch details of the selected server
          g_form.getReference('your_reference_field_name', function(server) {
              // Check if the multiline string variable field is empty
              if (g_form.getValue('your_multiline_string_field') === '') {
                  // Populate the server_result field with the sys_class_name display value
                  g_form.setValue('server_result', server.sys_class_name.getDisplayValue());
              }
          });
      }
      
      • Replace your_reference_field_name with the exact name of your reference field.
      • Replace your_multiline_string_field with the exact name of your multiline string field.
      • Ensure server_result is the correct field name for the target string field where you want to populate the sys_class_name.

    Key Points:

    • Client-side Logic: Since a client script is user-side logic, it ensures that interactions happen dynamically when the user changes the reference field.
    • getReference() Method: This is used to asynchronously get the details of the selected reference record. It takes a callback function to process the data once fetched.
    • Condition Check: The condition if (g_form.getValue('your_multiline_string_field') === '') ensures that the logic only runs and populates server_result if the multiline string field is empty.

    Testing:

    • After implementing the script, test it in a ServiceNow development environment.
    • Select a server from the reference field and see if server_result is populated correctly when the multiline field is empty.

    This setup should correctly populate the server_result field based on your requirements, improving the form interaction dynamically.

  7. User

    not working how to do it via script include and catalog client scri[t

  8. Assistant

    To achieve the desired behavior using a Script Include and a Catalog Client Script in ServiceNow, you can follow these steps. The Script Include will handle server-side logic, and the Catalog Client Script will manage the client-side UI interaction. Here's a comprehensive approach:

    Step 1: Create a Script Include

    1. Navigate to: System Definition > Script Includes.

    2. Click on: New to create a new Script Include.

    3. Configure the Script Include:

      • Name: Provide a name like ServerInfoHelper.
      • API Name: This should be the same as the Script Include name (ServerInfoHelper) for easy access.
      • Accessible from: Ensure it's set to All application scopes if needed across applications.
      • Active: Ensure this is checked.
      • Client callable: Check this option because you'll be calling this from the client script.
    4. Script: Insert the following script in the Script section:

      var ServerInfoHelper = Class.create();
      ServerInfoHelper.prototype = {
          initialize: function() {},
      
          getServerClassName: function(serverSysId) {
              if (!serverSysId) {
                  return '';
              }
      
              var serverGR = new GlideRecord('cmdb_ci_server');
              if (serverGR.get(serverSysId)) {
                  return serverGR.sys_class_name.getDisplayValue();
              }
      
              return '';
          },
      
          type: 'ServerInfoHelper'
      };
      

    Step 2: Create a Catalog Client Script

    1. Navigate to: Service Catalog > Catalog Definition > Maintain Items.

    2. Open the Catalog Item where you want this logic to apply.

    3. Switch to: Catalog Client Scripts related list.

    4. Click on: New to create a new Catalog Client Script.

    5. Configure the Catalog Client Script:

      • Name: Provide a name like Populate Server Result.
      • Catalog Item: Ensure it’s linked to the correct catalog item.
      • UI Type: Choose All.
      • Type: Select OnChange.
      • Variable name: Choose your reference field variable (e.g., server_reference_field).
    6. Script: Insert the following script in the Script field:

      function onChange(control, oldValue, newValue, isLoading) {
          if (isLoading || !newValue) {
              return;
          }
      
          // Check if the multiline string variable is empty
          var multilineValue = g_form.getValue('your_multiline_string_field');
          if (!multilineValue) {
              // Call the Script Include
              var ga = new GlideAjax('ServerInfoHelper');
              ga.addParam('sysparm_name', 'getServerClassName');
              ga.addParam('sysparm_serverSysId', newValue);
      
              ga.getXMLAnswer(function(response) {
                  var displayValue = response;
                  g_form.setValue('server_result', displayValue);
              });
          }
      }
      
      • Replace your_multiline_string_field with the exact name of your multiline variable field.
      • Replace server_reference_field and server_result with the correct variable names for your reference field and result field.

    Explanation

    • Script Include: The Script Include (ServerInfoHelper) processes server-side logic to fetch the sys_class_name of the server using its sys_id.
    • GlideAjax: Within the Catalog Client Script, GlideAjax is used to call the Script Include asynchronously. This fetches the server class name without refreshing the page.
    • Asynchronous Update: The getXMLAnswer callback ensures that the result is processed and set to the server_result field only after receiving it from the server.

    Testing

    • After implementing these scripts, test this setup in a ServiceNow development environment.
    • Select a server from the reference field and ensure the server_result field is populated correctly with the sys_class_name when the multiline field is empty.

    This approach leverages both client-side scripting for interactivity and server-side logic for data retrieval, offering a comprehensive solution to your requirement.

  9. User

    i make this script include and a catalog client script to check if the onchange field has no newValue then get the sysid of selected server selected in the field called please_select_the_server_name and search it in cmdb_ci_server table and take the display value of sys_class_name field and populate it in server_result field in string

    getServerClassName: function() { var result = {};

        var grciTable = new GlideRecord('cmdb_ci_server');
    	var selectedCIValue = this.getParameter('sysparm_selectedCI');
    	if (grciTable.get(selectedCIValue)) {
            result.class_name = grciTable.getDisplayValue("sys_class_name");
    
        }
    
        return JSON.stringify(result);
    },
    

    and a catalog client script

    function onChange(control, oldValue, newValue, isLoading) { if (isLoading || newValue == '') { //alert('Server is: '+serverDetails); return; }

    if (!newValue) {
        var serverDetails = g_form.getValue('please_select_the_server_name');
        var ciDetails = new GlideAjax('PEP_cmdb_class_name_populate');
        ciDetails.addParam('sysparm_name', 'getServerClassName');
        ciDetails.addParam('sysparm_selectedCI', serverDetails);
        ciDetails.getXMLAnswer(function(result) {
            var response = JSON.parse(result);
            g_form.setValue("server_result", response.class_name);
        });
    }
    

    }

  10. Assistant

    The script include and catalog client script you've provided seem mostly on the right track, but there are a few issues, particularly around the condition if (!newValue) in the client script. This condition is unlikely to trigger because newValue == '' is already checked. Let's refine and correct the logic:

    Script Include

    Your getServerClassName function in the Script Include appears correct with only minor clarifications needed:

    1. Ensure the Script Include is marked as Client Callable.
    2. Double-check that the Script Include is active and accessible.

    Here's the Script Include for reference:

    var ServerInfoHelper = Class.create();
    ServerInfoHelper.prototype = {
        initialize: function() {},
    
        getServerClassName: function() {
            var result = {};
            var grciTable = new GlideRecord('cmdb_ci_server');
            var selectedCIValue = this.getParameter('sysparm_selectedCI');
            if (grciTable.get(selectedCIValue)) {
                result.class_name = grciTable.getDisplayValue("sys_class_name");
            }
            return JSON.stringify(result);
        },
    
        type: 'ServerInfoHelper'
    };
    

    Catalog Client Script

    To fetch and display the sys_class_name display value from cmdb_ci_server when the please_select_the_server_name field changes, make sure the logic flow is as follows:

    1. Use getXMLAnswer to get data from the Script Include on value change of the reference field.
    2. Update the condition in onChange to check the initial loading phase correctly so that the AJAX call executes if necessary.

    Here's how the corrected Catalog Client Script should look:

    function onChange(control, oldValue, newValue, isLoading) {
        if (isLoading) {
            return;
        }
    
        if (newValue) {
            // Only call when there is a new value
            var ciDetails = new GlideAjax('ServerInfoHelper');
            ciDetails.addParam('sysparm_name', 'getServerClassName');
            ciDetails.addParam('sysparm_selectedCI', newValue);
    
            ciDetails.getXMLAnswer(function(result) {
                var response = JSON.parse(result);
                g_form.setValue("server_result", response.class_name || '');
            });
        }
    }
    

    Points to Consider

    • Correct Reference: Make sure the ServerInfoHelper is the correct name for your Script Include.
    • Calling the Script Include: The client script checks newValue to execute only when a CI is selected (not when it's removed or initially empty).
    • JSON Parsing: The JSON parsing handles returned values safely, with a default fallback if class_name is not provided.
    • Field Names: Double-check the names please_select_the_server_name and server_result are exactly matching the variable names in your catalog item.

    Troubleshooting

    • Debugging: Use console.log(result) instead of alert() for better debugging in the client script.
    • Testing: Test this set up in a non-production environment. Use browser developer tools to check for potential errors in the console, especially related to AJAX requests.

    Use these adjustments to ensure your scripts run smoothly and achieve the desired functionality of updating the form dynamically.