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

In servicenow i wrote this business rule to populate the value in string field but dot…

  1. User

    In servicenow i wrote this business rule to populate the value in string field but dot walking through all the reference fields . But it is not working, please fix this......(function executeRule(current, previous /null when async/) 1 var assignedTo - current.assigned_to; var dept; if (assignedTo) var userGR = new GlideRecord('sys_user') userGR.addQuery('sys_id', assignedTo.sys_id); userGR.query(; if (userGR.next() f dept = userGR.getValue('department'); if (dept) var deptGr = new GlideRecord( 'cmn_department'); deptGr.addQuery('name', dept); deptGr.query(; if (deptGr.next()) var bussinessUnit = deptGr.getValue('business_unit'); if (bussinessUnit) f var bu = new GlideRecord('business_unit'); bu.addQuery('name', bussinessUnit); deptGr.query (; if (bu.next() ( var buHead = bu.getValue("bu_head") current.u_bu_head = buHead,toString();

  2. Assistant

    It looks like the code you have provided has several syntax and structural issues. Below is a corrected version of your business rule script that follows best practices for GlideRecord operations along with proper syntax.

    (function executeRule(current, previous /*null when async*/) {
        var assignedTo = current.assigned_to; 
        var dept; 
        if (assignedTo) {
            var userGR = new GlideRecord('sys_user');
            userGR.addQuery('sys_id', assignedTo.sys_id);
            userGR.query();
            if (userGR.next()) {
                dept = userGR.getValue('department');
                if (dept) {
                    var deptGr = new GlideRecord('cmn_department'); 
                    deptGr.addQuery('sys_id', dept);
                    deptGr.query();
                    if (deptGr.next()) {
                        var businessUnit = deptGr.getValue('business_unit');
                        if (businessUnit) {
                            var bu = new GlideRecord('business_unit'); 
                            bu.addQuery('sys_id', businessUnit); 
                            bu.query();
                            if (bu.next()) {
                                var buHead = bu.getValue("bu_head"); 
                                current.u_bu_head = buHead; // Assuming 'u_bu_head' is a field in the current record
                            }
                        }
                    }
                }
            }
        }
    })(current, previous);
    

    Explanation:

    1. Variable Declaration and Initialization: Start by creating and initializing the assignedTo variable from current.assigned_to.
    2. Check for assignedTo: Ensure assignedTo is valid/exists before performing further operations.
    3. User GlideRecord Query:
      • Create a new instance of GlideRecord for the sys_user table.
      • Query the sys_user table for the specific assigned_to.
    4. Retrieve Department: If the user record is found, get the value for department.
    5. Department GlideRecord Query:
      • Create a new instance of GlideRecord for the cmn_department table.
      • Query for the specific department.
    6. Retrieve Business Unit: If the department record is found, get the value for business_unit.
    7. Business Unit GlideRecord Query:
      • Create a new instance of GlideRecord for the business_unit table.
      • Query for the specific business unit.
    8. Retrieve Business Unit Head: If the business unit record is found, get the value for bu_head and set it to current.u_bu_head.

    Make sure that field names like u_bu_head, business_unit, and other custom fields exist or adjust these according to your data model in ServiceNow. Note that the toString() method is generally unnecessary for setting a string field in ServiceNow, as getValue already returns a string.

  3. User

    I wrote this client script in servicenow , but it shows undefined in string field function onChange(control, oldValue, newValue, isloading, isTemplate) f if (isloading || newValue === return; if (gform.getValue('install_status') == 2 |l g_form.getValue('install_status') =6 || g_form.getValue(install_ status') -- 9) return; g_form.getReference('department', setBuHead); function setBuHead(assigned) if (assigned g_form.setValue('u_bu_head', assigned.business_unit.bu_head);

  4. Assistant

    Your script has syntax errors and a few logical issues that need correction. Here’s a revised version of your client script that should work as expected:

    function onChange(control, oldValue, newValue, isLoading, isTemplate) {
        if (isLoading || newValue === '') {
            return;
        }
    
        // Check the value of the 'install_status' field
        var installStatus = g_form.getValue('install_status');
        if (installStatus == 2 || installStatus == 6 || installStatus == 9) {
            return;
        }
    
        // Get the reference data for the 'department' field
        g_form.getReference('department', setBuHead);
    
        // Function to set the BU Head based on department's business unit
        function setBuHead(department) {
            if (department && department.business_unit) {
                g_form.getReference('business_unit', setBuHeadFromBusinessUnit);
            } else {
                g_form.setValue('u_bu_head', '');
            }
        }
    
        // Function to set the BU Head based on business unit
        function setBuHeadFromBusinessUnit(businessUnit) {
            if (businessUnit && businessUnit.bu_head) {
                g_form.setValue('u_bu_head', businessUnit.bu_head);
            } else {
                g_form.setValue('u_bu_head', '');
            }
        }
    }
    

    Explanation:

    1. Condition for isLoading and newValue:

      • Ensure the script exits if the form is loading or if the new value is empty.
    2. Getting the Install Status:

      • Use g_form.getValue('install_status') to check the value of the install_status field. Return if its value is 2, 6, or 9.
    3. Reference Lookup for Department:

      • Use g_form.getReference('department', setBuHead); to get the detailed record for the department field. This will automatically call the setBuHead function and pass the referenced department record as an argument.
    4. Function setBuHead to Handle Business Unit Reference:

      • Ensure that the department exists and has a business_unit.
      • If it does, call g_form.getReference('business_unit', setBuHeadFromBusinessUnit); to get the detailed record for the business_unit.
      • If the department or business_unit is not found, clear the u_bu_head field.
    5. Function setBuHeadFromBusinessUnit to Set BU Head:

      • Ensure that the business_unit exists and has a bu_head.
      • Set the value of the u_bu_head field to the bu_head of the related business unit.
      • If the business_unit or bu_head is not found, clear the u_bu_head field.

    Feel free to adjust any field names (u_bu_head, business_unit, install_status, department) and their values according to your specific instance configuration. This script assumes install_status, department, and u_bu_head are valid field names on the form's table.

  5. User

    Not working

  6. Assistant

    Let's thoroughly debug and fix the script by ensuring the following aspects:

    1. Correct function signature.
    2. Proper checking of values.
    3. Correct handling of reference lookups.
    4. Syntax errors, especially in the g_form methods.

    Here's another attempt to address the issues comprehensively:

    function onChange(control, oldValue, newValue, isLoading, isTemplate) {
        if (isLoading || newValue === '') {
            return;
        }
    
        // Check whether install_status is 2, 6, or 9
        var installStatus = g_form.getValue('install_status');
        if (installStatus == '2' || installStatus == '6' || installStatus == '9') {
            return;
        }
    
        // Get the reference data for the 'department' field
        g_form.getReference('department', function(department) {
            if (department && department.business_unit) {
                // Get the reference for the business unit
                g_form.getReference('business_unit', function(businessUnit) {
                    if (businessUnit && businessUnit.bu_head) {
                        g_form.setValue('u_bu_head', businessUnit.bu_head);
                    } else {
                        g_form.setValue('u_bu_head', '');
                    }
                }, department.business_unit);
            } else {
                g_form.setValue('u_bu_head', '');
            }
        });
    }
    

    Key Changes and Fixes:

    1. Correct Handling of Install Status Check:

      • Ensure installStatus is compared as a string. The values for install_status might be strings, so comparisons are done with '2', '6', and '9'.
    2. Handling Reference Lookup Values:

      • g_form.getReference uses a callback function which ensures proper handling of asynchronous data retrieval.
    3. Nested Callbacks for Field References:

      • The first g_form.getReference call retrieves the department record.
        • If the department.business_unit exists, make another g_form.getReference call to get the business_unit.
        • Set the u_bu_head value based on the nested lookup results.
    4. Clear u_bu_head if Reference Lookup Fails:

      • If the references do not return the expected objects, clear u_bu_head to avoid showing undefined or stale data.

    Ensuring Configuration in ServiceNow:

    • Ensure that department is a reference field pointing to the correct table.
    • Ensure that business_unit is a reference field within the cmn_department table.
    • Ensure u_bu_head is the correct field name in the form where the BU Head should be populated.

    Testing:

    1. Open the Form:

      • Make sure the form loads without JavaScript errors.
    2. Change the Department or Trigger the Script via UI:

      • Make a change that should trigger this onChange script to ensure that it executes and populates u_bu_head.

    Debugging Potential Issues:

    • Add console.log statements to verify data within the script if it still doesn't work.

    Example debugging addition:

    console.log('Department:', department);
    console.log('Business Unit:', department.business_unit);
    console.log('BU Head:', businessUnit.bu_head);
    

    Observe logs in the browser console for further troubleshooting. If there are still issues, examining the browser console output and debugging further within the ServiceNow scripting environment will help pinpoint the exact problem.