Skip to content
TheChatArchiveThe Chat Archive
gpt-4-1106-preview· openaiHugging Face Suzhen/CodeChat

I have a custom table which contains four columns: Application Department Approver AD…

  1. User

    I have a custom table which contains four columns:

    Application

    Department

    Approver

    AD Group

    On the catalog item, the user selects the desired application and department. I then have an approval that uses these two variables to look up and set the the approver from the table. This works great. I now want to add a hidden or read-only field that will take these same two variables from the item and look and and set this value.

    So if user picks Application A and Department 1, the new variable should be set to something. If they pick Application B and Department 2, then the new variable would be set to whatever the AD value is in the lookup table.

  2. Assistant

    It seems like you're working with a service management tool or workflow system, possibly something like ServiceNow, where you're creating a service catalog item that relies on an underlying custom table for conditional logic.

    Assuming you have a system where you can write scripts or some logic to carry out these actions, here's what you generally need to do:

    1. Have an event listener or a script that triggers when the 'Application' and 'Department' fields are set or changed.
    2. Perform a lookup to the custom table using these two values as filters to retrieve the corresponding 'Approver' and 'AD Group' values.
    3. Set the 'Approver' in your approval definition, which you've already implemented.
    4. Set the 'AD Group' in a new field which is either hidden or read-only on your catalog item.

    Here's a conceptual example of how you might implement this logic in a JavaScript-based engine, which is common in service management platforms:

    // Assuming you have variables application and department 
    // which store user's selections
    
    function updateFields(application, department) {
        // fetch the record from the custom table based on the application and department
        var adGroupValue = getADGroupFromCustomTable(application, department);
        
        // Assuming you have a function to set the field value in your form
        // Set the AD Group field with the fetched value
        setADGroupField(adGroupValue);
    }
    
    function getADGroupFromCustomTable(application, department) {
        // Logic to query your custom table with the application and department
        // returning the AD Group associated with those choices
        // (The actual implementation will depend on the system you are using)
        
        /* Psuedo-code representing the query
        var record = CustomTable.query({
            'Application': application,
            'Department': department
        }).fetch();
        
        if (record) {
            return record.ADGroup;
        } else {
            // Handle case where no record matches the criteria
            return 'Default or error value';
        }
        */
    }
    
    // A function to set the AD Group field value
    function setADGroupField(value) {
        // Again the implementation depends on your system
        // This is just conceptual
        /*
        var adGroupField = Form.getField('ADGroup');
        adGroupField.setValue(value);
        if(hidden_or_readOnly) {
            adGroupField.setReadOnly(true); // Or use setVisibility(false) for hidden
        }
        */
    }
    
    // Add the event listener or binding for when application and department are set
    // Again, this depends on your platform
    /*
    Form.getField('application').onChange(function(newApplication) {
        var department = Form.getField('department').getValue();
        updateFields(newApplication, department);
    });
    
    Form.getField('department').onChange(function(newDepartment) {
        var application = Form.getField('application').getValue();
        updateFields(application, newDepartment);
    });
    */
    
    

    Remember that the actual functions and methods you'll use will vary according to the specific platform you're using, so you'll need to consult the documentation for the correct API calls.

    Finally, once you have the code ready, it's important to test it thoroughly to ensure that it behaves correctly for all combinations of applications and departments that a user can select.

  3. User

    When Incident is promoted to be Major Incident create Problem Automatically with parent is incident record and priorty is high in servicenow

  4. Assistant

    In ServiceNow, to automate the creation of a Problem record when an Incident is promoted to a Major Incident, you will likely need to use a Business Rule or a Flow Designer flow, depending on your preference and the complexity of your requirement.

    Here's how you can create a Business Rule to achieve this:

    1. Go to the Business Rules module by navigating to System Definition > Business Rules.
    2. Click on "New" to create a new Business Rule.
    3. Set the name of the Business Rule, for example, "Create Problem on Major Incident".
    4. Choose the table you want this Business Rule to run on, which should be the Incident table (incident).
    5. In the When to run tab, set up the conditions under which this Business Rule will execute. You will likely want to trigger it when the Incident record is updated, and the Major Incident field has been changed to true.
    6. In the Advanced tab, check the "Advanced" checkbox to write a script.
    7. Write a script that checks if the Incident's Major Incident field is set to true and if so, creates a new Problem record. Here is an example script that you might use (please note that you need to adhere to your instance's configuration, which may include custom fields or processes):
    (function executeRule(current, previous /*null when async*/) {
        // Check if the Incident is promoted to a Major Incident
        if (current.major_incident == 'true') {
            
            // Create a new Problem record
            var problem = new GlideRecord('problem');
            problem.initialize(); // Prepare a new record
            problem.short_description = current.short_description;
            problem.description = current.description;
            problem.parent_incident = current.sys_id; // Set the reference to the Incident
            problem.priority = 1; // Set to '1 - High' as per the requirement
            // populate other necessary fields...
            
            var problemID = problem.insert(); // Create the new Problem record and store its sys_id
            
            // Optionally, you could also update the Incident record with a reference to the new Problem
            if (problemID) {
                current.problem_id = problemID;
                current.update();
            }
        }
    })(current, previous);
    
    1. Configure the conditions under which the script should run and any other options the Business Rule provides.
    2. Save the Business Rule.

    This Business Rule will now be triggered every time an Incident is updated. If the Incident is promoted to a Major Incident, a new Problem record with the specified fields will be created and linked to the Incident.

    Alternatively, if you prefer to use ServiceNow's Flow Designer, you would:

    1. Navigate to Flow Designer (Flow Designer > Designer).
    2. Create a new Flow.
    3. Add a Trigger that listens for updates on the Incident table.
    4. Set Conditions for when the Incident is promoted to a Major Incident.
    5. Add Actions to create a new Problem record with the Incident's information mapped to the relevant fields.
    6. Publish the Flow.

    Regardless of the method you choose, please tailor the script or flow conditions and actions to your specific instance configuration and needs. Always test in a sub-production instance before deploying to production.

  5. User

    table for business rule and best when to run condition

  6. Assistant

    In ServiceNow, Business Rules are set on a specific table, and their conditions determine when they should run. If you want to create a Problem record when an Incident is promoted to a Major Incident, you would configure your Business Rule as follows:

    Table for the Business Rule:

    • Table: Incident [incident]. You should apply the Business Rule to the Incident table because you are monitoring for changes in Incident records.

    Best "When to run" conditions:

    • When: Before update. You should use the "before update" timing for efficiency, to minimize database operations, and to ensure that the changes are all saved at once. This is especially important if your Business Rule updates the current Incident record; the "before" timing allows these changes to be committed as part of the original transaction.

    • Conditions: The specific condition you would set will depend on how your instance defines Major Incidents. Typically, you might have a field on the Incident form that indicates that the Incident has been promoted to a Major Incident. Assume this field is a checkbox and is named 'major_incident'. You would set the condition so that the Business Rule runs only when the 'major_incident' field is changed to true.

    • Filter Conditions: You would define the filter conditions in the Business Rule's condition editor. An example of the conditions might be:

      • major_incident changes to true

    Here is a summary of what your Business Rule setup might look like:

    1. Name: Create Problem for Major Incident
    2. Table: Incident [incident]
    3. When to run:
      • Execute when: Before
      • Insert: false
      • Update: true
      • Delete: false
      • Query: false
    4. Conditions:
      • major_incident changes to true
    5. Advanced: true
    6. Script:
      (function executeRule(current, previous /*null when async*/) {
          // Make sure we only act on the condition that the major_incident field was set to true
          if (current.major_incident == 'true' && previous.major_incident != 'true') {
              var problem = new GlideRecord('problem');
              problem.initialize();
              problem.short_description = current.short_description;
              problem.description = current.description;
              problem.parent_incident = current.sys_id; // Relation to the parent incident
              problem.priority = '2'; // Assuming '2' corresponds to High priority in your instance
              problem.insert(); // Create problem record
          }
      })(current, previous);
      

    Remember to test the Business Rule thoroughly in a development or testing environment before implementing it in a production environment.

    Finally, if your instance has any specific custom fields or classifications for major incidents or if the Incident table has been customized, you might need to adjust the condition logic accordingly.

  7. User

    if (current.major_incident == 'true' && previous.major_incident != 'true') { var problem = new GlideRecord('problem'); problem.initialize(); problem.short_description = current.short_description; problem.description = current.description; problem.parent_incident = current.sys_id; // Relation to the parent incident problem.priority = '2'; // Assuming ‘2’ corresponds to High priority in your instance problem.insert(); // Create problem record } fix this code to create a problem record with respect to incident record when major incident state of the incident is accepted

  8. Assistant

    To fix the code to create a Problem record only when the Major Incident state of an Incident is set to "Accepted", you would need to adjust the condition to check specifically for that state. In ServiceNow, the field values like "Major Incident State" are usually represented by specific integers or sys_ids, depending on how the field is set up.

    Let's assume that "Accepted" is represented by a specific value, and you have a field named major_incident_state. You would want to check that this field has been changed to the value representing "Accepted". The actual value might differ based on your instance's setup, so ensure you use the correct identifier.

    Here's the updated script:

    (function executeRule(current, previous /*null when async*/) {
        // Assuming '2' is the value representing the 'Accepted' state in major_incident_state field
        var ACCEPTED_STATE_VALUE = '2'; // You need to replace '2' with the actual value from your instance
    
        // Check if the Major Incident State is 'Accepted' and has changed to this state
        if (current.major_incident_state == ACCEPTED_STATE_VALUE && (previous == null || previous.major_incident_state != ACCEPTED_STATE_VALUE)) {
            var problem = new GlideRecord('problem');
            problem.initialize();
            problem.short_description = current.short_description;
            problem.description = current.description;
            problem.parent = current.sys_id; // Assuming 'parent' is the correct reference field for the parent incident
            
            // Assuming '2' corresponds to High priority in your instance
            // Retrieve the actual priority value using the Incident's impact and urgency or concatenation if necessary
            var highPriorityValue = getHighPriorityValue(current); // Custom function to determine priority
            problem.priority = highPriorityValue; 
            
            var newProblemID = problem.insert(); // Create Problem record and store its sys_id
            
            // If you want to update back the Incident with the related Problem ID, you can do so here:
            if(newProblemID) {
                current.problem_id = newProblemID; // Assuming 'problem_id' is the correct reference field on the Incident
                current.update(); // Only do this if absolutely necessary, to avoid recursion
            }
        }
        
        // Custom function to get the equivalent priority value for 'High' based on current configuration
        function getHighPriorityValue(currentIncident) {
            // For demonstration purposes, simply returning '2'. Replace with your logic as needed.
            return '2';
        }
        
    })(current, previous);
    

    Important notes:

    • Check References: Ensure parent and problem_id are the correct field names on the problem and incident tables, respectively. The actual field names may vary based on your ServiceNow instance's configuration.

    • Priority Logic: The line var highPriorityValue = getHighPriorityValue(current); assumes that you need logic to determine what "High" priority is. If High priority is a static value in your instance, you can assign it directly, but often priority is a computed value based on impact and urgency. Replace this with the appropriate logic for your instance.

    • Update Carefully: Be careful when using current.update() as it can lead to recursion if your Business Rule is not configured to prevent running on subsequent updates. You'll want to make sure this line is needed and use conditions to avoid recursion.

    Finally, check your instance for the exact value representing the "Accepted" state for a Major Incident. The value '2' is being used here as a placeholder. Look up the choice list for the 'major_incident_state' field in your instance to get the correct value.

  9. User

    f (current.major_incident_state == 'accepted' && previous.major_incident_state !=='accepted') { var problem = new GlideRecord('problem'); problem.initialize(); problem.short_description = current.short_description; problem.description = current.description; problem.parent_incident = current.sys_id; // Relation to the parent incident problem.insert(); // Create problem record } i got this error while using this business rule code please fix this Unique Key violation detected by database ((conn=91865) Duplicate entry '5aa475bb47f40210d14d82b4116d433b' for key 'PRIMARY')

  10. Assistant

    The error message you're encountering, "Unique Key violation detected by database," suggests that the script is trying to insert a record with a value that already exists for a unique column in the table, typically the ‘sys_id’.

    The line problem.parent_incident = current.sys_id; is setting the parent_incident field in the problem record. This error may be occurring if parent_incident is meant to be a unique reference back to the incident, and there's already a problem record referencing the same incident.

    However, ServiceNow does not restrict the problem table's parent field in this way by default, so you should ensure the parent_incident field you’re referencing is actually on the problem table and has the correct attributes.

    To resolve this error, check the following:

    1. Confirm the Field Name: Ensure that parent_incident is the correct field name for the reference to the Incident table on the Problem table and that this field is not marked as unique or does not trigger any business rule or workflow that may cause duplication.

    2. Avoid Direct sys_id Duplication: Do not copy sys_id from one record to another as it's a unique identifier for each record.

    3. Check for Customization: If your instance has been customized and parent_incident has been set up with unique constraints, you may need to adjust your approach to ensure you are not violating those constraints.

    4. Review Business Logic: Look for any other business rules, client scripts, workflows, or other automation in your instance that might be interfering or attempting to create additional records in such a way that would result in a unique key violation.

    Given the common out-of-the-box configuration in ServiceNow, the field name for the reference to the parent incident should probably just be parent. Here's the updated script reflecting that change:

    (function executeRule(current, previous /*null when async*/) {
        // Check if the Major Incident State has changed to 'accepted'
        if (current.major_incident_state == 'accepted' && previous.major_incident_state != 'accepted') {
            var problem = new GlideRecord('problem');
            problem.initialize();
            problem.short_description = current.short_description;
            problem.description = current.description;
            problem.parent = current.sys_id; // Ensure this is the correct reference field name
            // Set additional fields if necessary, such as impact, urgency, category, etc.
            problem.insert(); // Create problem record
        }
    })(current, previous);
    

    Please take a cautious approach by first testing this in a non-production environment, and make sure to backup and understand your current configurations, including any potential customizations, before making changes. If you continue to face issues, you may need to contact your system administrator or seek support from ServiceNow directly, as there may be specific configurations affecting this behavior.

  11. User

    I have requirement if incident assignment group is "Application Development" . then the incident is only visible to the members of assignment group only . in servicenow

  12. Assistant

    In ServiceNow, access to records such as Incidents is controlled by Access Control Rules (ACLs). To meet your requirement where an Incident assigned to the "Application Development" assignment group should only be visible to its members, you'll need to set up an appropriate ACL on the Incident table.

    Here is a general approach to setting this up:

    1. Identify or Create the Assignment Group: Ensure that you have an existing group named "Application Development" in ServiceNow or create one if it doesn't exist. Also, make sure that all intended users are members of this group.

    2. Create a New ACL for the Incident Table:

      • Go to System Security > Access Control (ACL) in the Application Navigator.
      • Click on "New" to create a new ACL.
      • Enter the following details:
        • Type: select "Record" (since you want to control who sees which Incident records).
        • Operation: select "Read" (you are controlling the read access to the Incident records).
        • Name: give your ACL a meaningful name, e.g., Read access control for Application Development group on Incident.
        • Table: select the "Incident" [incident] table.
    3. Create the Condition for the ACL:

      • Under Conditions, set up a condition that matches Incidents where the assignment group is "Application Development". You may need to use the "Advanced" view to write a script if a straightforward condition doesn't suffice.

    Here is a simple example of a script you might use in the Advanced condition:

    (function executeRule(current, previous /*null when async*/) {
        // Get the sys_id of the "Application Development" group
        var appDevGroupSysId = 'YOUR_GROUP_SYS_ID'; // Replace with actual sys_id of the group
        
        // If the assignment group of the current record matches "Application Development"
        // and the current user is not a member of that group, deny access
        if (current.assignment_group == appDevGroupSysId && !current.assignment_group.members[current.user]) {
            return false; // Deny access
        }
        
        return true; // Default to allow access
    })(current, previous);
    
    1. Set the ACL Script: In the "Script" field, write your script similar to the above.

    2. Test Your ACL: Test to ensure that it is working as intended by using test accounts that are members and not members of the "Application Development" group.

    Remember that when you use scripts in ACLs, you're responsible for ensuring they execute efficiently. Inefficient scripts in ACLs can seriously degrade system performance.

    Also, be cautious when restricting access to ensure that your rules do not interfere with other necessary operations, such as workflows or system processes that might need to interact with Incident records.

    Because of the complexity and potential impacts of ACLs on the entire system, it is highly recommended that this work be performed by a ServiceNow administrator with a thorough understanding of ServiceNow ACLs and their implications. Testing thoroughly in a sub-production environment before deploying to production is essential to avoid unintended consequences.

  13. User

    Write a Client script to validate user input on a custom form?

  14. Assistant

    A client script in ServiceNow is used to perform client-side actions and validations on forms. You can use an onSubmit client script to validate user input before the data is sent to the server. Below is a generic example of how you can write an onSubmit client script to validate user input on a custom form in ServiceNow:

    1. Navigate to Custom Form:

      • Open the form where you want to add the validation client script.
    2. Add New Client Script:

      • Go to Form Design or Customize Form from the form context menu.
      • In the related links at the bottom of the form, click on "Client Scripts".
    3. Fill out Client Script Form:

      • Click "New" to create a new client script.
      • Fill out the form with the following information:
        • Name: Give your client script a meaningful name, e.g., “Validate User Input”.
        • Table: Choose the table that your custom form is based on.
        • Type: Select onSubmit since you want to perform validation when the form is submitted.
        • Script: Enter your JavaScript code to validate user input (example provided below).
    4. Example Client Script:

    function onSubmit() {
       // Replace 'field_name' with the actual field you want to validate
       var userInput = g_form.getValue('field_name');
    
       if (!validateInput(userInput)) {
          // If validation fails, show an error message and prevent form from submitting
          g_form.addErrorMessage('Input for field name is invalid. Please correct your input.');
          return false;
       }
       return true; // Return true to allow the form to be submitted
    }
    
    // Custom validation function
    function validateInput(input) {
       // Replace this pseudocode with your validation logic
       if (input === '' || someOtherValidationCondition(input)) {
           // Validation failed
           return false;
       }
       // Validation passed
       return true;
    }
    

    Replace field_name with the name of the field you want to validate and implement the specific validation logic you need in the validateInput function.

    The g_form.getValue('field_name') function gets the value of the specified field when the form is submitted. The g_form.addErrorMessage('Your error message') function displays a custom error message to the user.

    1. Activate and Save:

      • Set the Active field to true if you want the client script to be active immediately.
      • Click "Submit" to save your new client script.
    2. Testing:

      • After you've set up your client script, test the form by entering both valid and invalid data to ensure that your validation works as expected.

    Remember that client scripts can have an impact on the user experience, so make sure that your validation logic is optimized and does not cause unnecessary delays or performance issues. Always test thoroughly on a development or staging instance before deploying scripts to production.

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