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

In servicenow, i have one choice field in sctask table and i want to populate it when…

  1. User

    In servicenow, i have one choice field in sctask table and i want to populate it when state

  2. Assistant

    In ServiceNow, if you want to automatically populate a choice field in the sc_task table when the state changes, you can achieve this using either a Business Rule or a Script Action depending on the event that you're targeting. Here's a general approach using a Business Rule, which is often appropriate for this kind of task:

    Steps to Create a Business Rule:

    1. Navigate to Business Rules:

      • Go to the ServiceNow main menu and type "Business Rules" in the filter navigator, then click on the "Business Rules" module under "System Definition."
    2. Create a New Business Rule:

      • Click the "New" button to create a new Business Rule.
    3. Configure the Business Rule:

      • Name: Give your Business Rule a meaningful name.
      • Table: Select sc_task from the table list since you want the rule to apply to SCTasks.
      • Advanced: Check this box to access the script section.
      • When to Run: Decide when you want the Business Rule to trigger:
        • Insert or Update
        • In most cases, you'll want to select "Update" since you're reacting to a change in state.
    4. Conditions:

      • Set the condition to check if the state has changed. For example:
        current.state.changes()
        
    5. Script:

      • Write a script to set the value of the choice field based on the state. For example:
        (function executeRule(current, previous /*null when async*/) {
            // Check if the state has changed to a specific value
            if (current.state == '3') { // Replace '3' with your specific state value
                // Set the choice field value
                current.your_choice_field = 'desired_choice_value'; // Replace with your field and value
            }
        })(current, previous);
        
    6. Save and Activate:

      • Once you've configured your Business Rule, click "Submit" to save it, and then ensure it's active (you may need to activate it if it's not automatically enabled).

    Testing:

    1. Test the Business Rule:

      • After activating the Business Rule, test it by changing the state of an SCTask record to see if the choice field updates as expected.
    2. Debugging:

      • If it doesn't work as expected, you might want to use gs.log() statements in your script to log information to the system log for debugging purposes.

    Best Practices:

    • Use conditions wisely to ensure the Business Rule only runs when necessary, preventing unnecessary processing.
    • Always test in a development or test environment before applying changes to production.
    • Consider the impact of the Business Rule on system performance, especially if dealing with a large number of records.

    By implementing these steps, you should be able to automatically populate a choice field in the sc_task table based on the state change.

  3. User

    I want that if state is closed incomplete, then make that field visible and mandatory via onchange client script and check if variable named as reason is new joinee and request_item.Item is asset allocation

  4. Assistant

    To achieve this functionality in ServiceNow, you can create an onChange client script for the state field in the sc_task table. This script will make a specific field visible and mandatory when the state is set to "Closed Incomplete" and certain conditions are met regarding the variable and item. Here's a step-by-step guide:

    Steps to Create an OnChange Client Script:

    1. Navigate to Client Scripts:

      • In the ServiceNow application navigator, type "Client Scripts" and select the module under "System Definition."
    2. Create a New Client Script:

      • Click the "New" button to create a new client script.
    3. Configure the Client Script:

      • Name: Enter a meaningful name for your client script.
      • Table: Select sc_task.
      • Type: Choose "onChange".
      • Field Name: Enter state as the field that triggers the script.
      • UI Type: Select the appropriate type (Desktop, Mobile/Service Portal, or All, depending on your use case).
    4. Script:

      • Write the script to handle the logic as described. Here is an example script:
      function onChange(control, oldValue, newValue, isLoading) {
          if (isLoading || newValue == '') {
              return;
          }
          
          // Constant values (Replace '7' and 'xxxxxxxx' with actual sys_ids or values)
          var CLOSED_INCOMPLETE = '7'; // Replace with the actual value used for "Closed Incomplete"
          var NEW_JOINEE_VARIABLE = 'new_joinee'; // Replace with the correct variable name
          var ASSET_ALLOCATION_ITEM = 'asset_allocation'; // Replace with the correct request item name
      
          // Check if state is "Closed Incomplete"
          if (newValue == CLOSED_INCOMPLETE) {
              // Access the GlideForm (g_form) to get field values
              var reasonValue = g_form.getValue(NEW_JOINEE_VARIABLE);
              var requestItemValue = g_form.getValue('request_item');
      
              // Use GlideAjax or GlideRecord to fetch request item details if needed
              // For example: check item in sc_req_item table
              // Ensure async call has completed if using GlideAjax
      
              if (reasonValue == 'new joinee' && requestItemValue == ASSET_ALLOCATION_ITEM) {
                  // Make your choice field visible and mandatory
                  g_form.setVisible('your_choice_field', true); // Replace with the correct field name
                  g_form.setMandatory('your_choice_field', true);
              } else {
                  // Reset field visibility and mandatory settings
                  g_form.setVisible('your_choice_field', false); // Again, replace with your field name
                  g_form.setMandatory('your_choice_field', false);
              }
          } else {
              // Reset field visibility and mandatory settings
              g_form.setVisible('your_choice_field', false);
              g_form.setMandatory('your_choice_field', false);
          }
      }
      
    5. Save the Client Script:

      • Click "Submit" or "Update" to save your client script.

    Important Considerations:

    • Sys_IDs and State Values: Ensure that you use the correct sys_id or state value for "Closed Incomplete", and verify the names of your variables and request items.

    • Field Names: Replace 'your_choice_field' with the actual field name you want to manipulate in the sc_task form.

    • Field Access: If you need to check information from related tables like sc_req_item, consider using a GlideAjax call to server-side scripts to fetch data, as direct server-side queries like GlideRecord are not available in client scripts.

    • Testing: Test your client script in a development environment to ensure it works as expected under all relevant circumstances.

    By following these steps, you should be able to dynamically update the visibility and mandatory status of your choice field based on the specified criteria.

  5. User

    Reason is a variable

  6. Assistant

    Since "Reason" is a variable within a catalog item associated with the sc_task table, you'll need to handle the variable as part of the catalog item (referred to as the Requested Item or sc_req_item). To access and check the value of a variable in an onChange client script for an sc_task, you will generally need to pass through the associated sc_req_item.

    Here is how you can achieve this functionality:

    Steps

    1. Identify Variable and Item:

      • Ensure you know the variable name (as it is stored in the variable set for the catalog item) and the exact name or unique identifier of the catalog item (in this case, "asset allocation").
    2. Set Up the Client Script:

      • You'll create an onChange client script on the sc_task table, which you will trigger by changes to the "state" field.
    3. Write the Script:

      Here’s an example client script:

      function onChange(control, oldValue, newValue, isLoading) {
          if (isLoading || newValue == '') {
              return;
          }
          
          var CLOSED_INCOMPLETE = '7'; // Replace with actual value for your Closed Incomplete state
          var EXPECTED_ITEM_NAME = 'asset_allocation'; // Use the item name or sys_id appropriately
      
          // Check if state is "Closed Incomplete"
          if (newValue == CLOSED_INCOMPLETE) {
              // Use GlideAjax to call a script include to get the variable value from sc_req_item
              var ga = new GlideAjax('RequestedItemUtils'); // Assuming a Script Include named RequestedItemUtils
              ga.addParam('sysparm_name', 'checkForNewJoinee');
              ga.addParam('sysparm_requestItem', g_form.getValue('request_item'));
              
              ga.getXMLAnswer(function(response) {
                  if (response == 'true') {
                      // Make the choice field visible and mandatory
                      g_form.setVisible('your_choice_field', true); // Replace with your actual field
                      g_form.setMandatory('your_choice_field', true);
                  } else {
                      // Set field to not visible and not mandatory
                      g_form.setVisible('your_choice_field', false);
                      g_form.setMandatory('your_choice_field', false);
                  }
              });
          } else {
              // Reset visibility and mandatory settings when state is not Closed Incomplete
              g_form.setVisible('your_choice_field', false);
              g_form.setMandatory('your_choice_field', false);
          }
      }
      

    Create a Script Include

    To fetch the variable from the sc_req_item, you will need a Script Include because you cannot directly use GlideRecord on the client-side. Here's a sample Script Include that might help:

    1. Navigate to Script Includes:

      • Go to the navigator and search for "Script Includes" under "System Definition."
    2. Create a New Script Include:

      • Create a new entry for this logic.
    3. Script Include Code:

      var RequestedItemUtils = Class.create();
      RequestedItemUtils.prototype = {
          initialize: function() {},
          
          checkForNewJoinee: function(requestItemSysId) {
              var reqItemGR = new GlideRecord('sc_req_item');
              if (reqItemGR.get(requestItemSysId)) {
                  var isNewJoinee = false;
                  
                  if (reqItemGR.cat_item.name == 'asset_allocation') { // Confirming the request item name
                      var itemVars = new GlideRecord('sc_item_option_mtom');
                      itemVars.addQuery('request_item', reqItemGR.sys_id);
                      itemVars.query();
                      
                      while(itemVars.next()) {
                          var questionGr = new GlideRecord('item_option_new');
                          if(questionGr.get(itemVars.sc_item_option) && questionGr.name == 'reason') {
                              isNewJoinee = itemVars.value == 'new joinee'; // Confirm the match
                              break;
                          }
                      }
                      
                      return isNewJoinee.toString();
                  }
              }
              return 'false';
          },
          
          type: 'RequestedItemUtils'
      };
      

    Considerations

    • Testing: Before deploying, ensure your script accurately checks values by testing in a non-production environment.
    • Security & Permissions: Make sure that your roles have the necessary permissions to read records from these tables and that the Script Include is accessible.
    • Performance: Minimize server calls from the client script, and use asynchronous calls smartly, as they can affect performance.

    By using a combination of a client script and a Script Include, you manage server-side logic efficiently while rendering UI changes effectively. This setup will allow the field to be visible and mandatory based on specific conditions met in your service catalog and associated tasks.

  7. User

    I want to do it via client script only

  8. Assistant

    To achieve your requirements using only a client script in ServiceNow, where you dynamically make a field visible and mandatory based on the state and specific catalog item variable values, you'll need to retrieve variable values directly from the catalog item associated with the service catalog task. Since direct scripting access to all the data on the server from a client script isn’t possible, you must ensure the data is accessible on the client side, potentially involving additional server calls via GlideAjax.

    However, to keep it strictly client-side without creating any server logic, you'll need to consider the limitations. Usually, the sc_task record alone doesn't have direct access to the catalog variables because they are associated with the request item (sc_req_item). But assuming you have control over the request item information and it can be loaded or passed to the client, here's a way you can proceed:

    Steps

    1. Make Catalog Variables Available to Client Scripts:

      • Ensure that "Reason" and any other required variables are included in the scratchpad or made available in some way, because by default, you can't access sc_req_item variables directly from the sc_task client script.
    2. Create the Client Script:

      • The client script will be an onChange script responding to changes in the "state" field. Here is an example script that you can adapt based on your setup:
      function onChange(control, oldValue, newValue, isLoading) {
          if (isLoading || newValue === '') {
              return;
          }
          
          var CLOSED_INCOMPLETE = '7'; // Replace with your specific value for "Closed Incomplete"
          var expectedVariableValue = 'new joinee'; // The value you're checking against
          var expectedRequestItemName = 'asset_allocation'; // The name you're checking
      
          if (newValue === CLOSED_INCOMPLETE) {
              // Simulate accessing catalog variables (in real scenarios, ensure they are available on the client-side)
              // If these variables exist and are set in some client-accessible manner:
              var reasonVar = g_form.getValue('reason_variable_name'); // Replace with correct client-accessible variable name
              var requestItemName = g_form.getValue('request_item_name_attribute'); // Again, replace with correct client-accessible value or method to fetch it
      
              // Check conditions
              if (reasonVar === expectedVariableValue && requestItemName === expectedRequestItemName) {
                  // Make the choice field visible and mandatory
                  g_form.setVisible('your_choice_field_name', true); // Replace with your actual choice field name
                  g_form.setMandatory('your_choice_field_name', true);
              } else {
                  // Reset the field
                  g_form.setVisible('your_choice_field_name', false);
                  g_form.setMandatory('your_choice_field_name', false);
              }
          } else {
              // Reset visibility and mandatory settings if the state is not Closed Incomplete
              g_form.setVisible('your_choice_field_name', false);
              g_form.setMandatory('your_choice_field_name', false);
          }
      }
      

    Key Points

    • Availability of Data: Normally, catalog item variables (sc_item_option values) aren't accessible directly through task forms. Accessing them strictly from the client side without additional server logic or pre-fetching can be challenging without using methods like GlideAjax.

    • Populate Variables: Consider pre-populating necessary catalog item data in a form of a scratchpad or passing them somehow to the client-side logic when the form loads.

    • Testing: Since manipulating catalog variables requires an understanding of how they'd be made available on the client, ensure that you thoroughly test which data is accessible to your forms to avoid script errors and ensure functionality.

    By using these strategies in combination with a better understanding of your specific ServiceNow environment and how your data is structured or made available, you can adapt this script to meet your needs.