Skip to content
The Chat Archive
gpt-4-0125-preview· OpenAI WildChat-4.8M (AI2)

var alm = new GlideRecord("almhardware");…

  1. User

    var alm = new GlideRecord("alm_hardware"); alm.addEncodedQuery('install_status=1^substatus!='); alm.query(); while(alm.next()){ alm.substatus = ''; alm.update(); }

    i wrote this fix script but when i go to form and check for substate it was showing only none choice. how to fix this and get all choices in substate asprevious

  2. Assistant

    It seems like your script is explicitly setting the substatus field to an empty string for all alm_hardware records where install_status is 1 and substatus is not empty. By doing so, you've essentially cleared out any previously set substatus values for these records.

    If the issue you're facing is that, after running the script, when you go to a form and try to select a value for substatus, you're only seeing "None" and not the full list of choices, it could be due to a couple of reasons unrelated to the script you ran. The script itself does not modify the choice list but only the values of the substatus field for each applicable record. Here are a few things you might want to check:

    1. Choice List Configuration: Ensure that substatus field's choice list is correctly configured. In ServiceNow, navigate to "System Definition" -> "Choice Lists", and look for entries related to the substatus field of alm_hardware. Verify that the choices are active and correctly set up.

    2. Dictionary Entry: Check the dictionary entry for the substatus field to ensure that it is correctly set to allow choices to be displayed. Go to "System Definition" -> "Dictionary" and search for the substatus field on alm_hardware. Make sure the field is configured to display choices.

    3. Field Attributes: Sometimes, field attributes can influence the display of options. In the dictionary entry for substatus, check if there are any attributes that could potentially restrict the choices being displayed.

    4. User Roles and Permissions: Verify that the user account you are testing with has the appropriate roles and permissions to view and edit the substatus choices. Lack of permissions could sometimes lead to not seeing all available field choices.

    5. Record-Specific Criteria: If the substatus choices are dynamically populated or restricted based on specific record criteria (such as script includes or business rules), ensure that these conditions are correctly met or configured.

    6. Cache Issues: Sometimes, UI issues in ServiceNow can be related to browser or server-side cache. Try clearing your browser cache or using an incognito/private browsing window to access the platform. You could also try performing a cache flush on your ServiceNow instance (please note, this action might have broader implications and should be done cautiously, preferably in a non-production environment or during off-hours).

    If you inadvertently removed values from substatus that you wish to restore, and if these values were important or relied upon by users or other processes, you might need to either manually restore them based on backup data, or if no backups are available, work with stakeholders to re-establish the desired substatus values per record. Always ensure you have a rollback plan or data backup before running scripts that modify records in bulk.

  3. User

    var alm = new GlideRecord(“alm_hardware”); alm.addEncodedQuery(‘install_status=1^substatus!=’); alm.query(); while(alm.next()){ alm.substatus = ‘’; alm.update(); }

    in servicenow After i wrote this fix script but when i go to form and check for substate it was showing only none choice. how to fix

  4. Assistant

    The script you've provided is setting the substatus field of certain alm_hardware records to an empty string. However, if you're now only seeing "None" as an option when trying to select a value for substatus on the form, and not the full list of choices that should be available for that field, then the issue likely doesn't stem directly from the script itself. Instead, it may be related to how the choice list for the substatus field is configured or potentially a form/view configuration issue.

    Here are steps to troubleshoot and potentially resolve the issue:

    1. Verify the Choice List Configuration

    • Navigate to System Definition > Choice Lists in the application navigator.
    • Filter the list by the "Table" column for alm_hardware and the "Element" column for substatus.
    • Ensure that the choices you expect to see are listed there and that they are active. If the choices are missing or inactive, that could explain why they're not appearing as options.

    2. Check the Dictionary Entry

    • Go to System Definition > Dictionary.
    • Search for the alm_hardware table and find the substatus field.
    • Ensure that the field type allows for choices (it should be a choice field, not a string field, unless it's using a dynamic choice list that's populated via scripting).
    • Check if there are any attributes set on the field that may restrict the choices. Attributes can sometimes influence how fields behave.

    3. Form Configuration

    • While on the form where you're experiencing the issue, click on the hamburger menu on the top left of the form header and select Configure > Form Design.
    • Find the substatus field on the form layout. Ensure it's added to the form and check if it has any specific configurations that may limit its choice options, like UI Policies or Client Scripts that could be manipulating the available options dynamically.

    4. Clear Cache

    Sometimes, cache issues can cause unexpected behavior in forms. Try clearing your browser’s cache or using an incognito/private window to see if the issue persists. Additionally, you can clear the server cache in ServiceNow by navigating to System Diagnostics > Clear Cache but do note that this action affects all users on the instance, so use it judiciously.

    5. Rollback If Necessary

    If the script unintentionally caused issues beyond just the observed symptoms or if you suspect that data might have been lost or corrupted, consider rolling back the changes. If you have a backup or a clone of your instance before the script was executed, use that to restore the affected data. If direct restoration isn't feasible, you might need to manually re-enter the correct substatus values for the affected records.

    Final Note

    If after trying the above steps the problem persists, consider reaching out to your instance's administrator (if you're not one) or ServiceNow support for further assistance. There may be instance-specific configurations or customizations affecting this behavior that are not immediately obvious.

  5. User

    i wrote below code in my catalog client script and it is working good for the condition if virtual server is found but when the virtual server not found it will need two click on submit button to submit the catalog request. please check the code and fulfill my requirement that if operational servers are found then a alert will show with the names and block the submission of catalog request and if no virtal server found then allow user to raise a catalog request without clicking two time on submit

    function onSubmit() { var scc = sessionStorage.getItem('scc') === 'true'; var scp = sessionStorage.getItem('scp') == 'true'; if(scc){ sessionStorage.removeItem('scc'); sessionStorage.removeItem('scp'); return scp; } var selectServer = g_form.getValue('select_server'); g_form.getReference('select_server', function(ref){ var ip_address = ref.ip_address; if(ip_address){ var ga = new GlideAjax('CheckOpStatus'); ga.addParam('sysparm_name', 'getParentNames'); ga.addParam('sysparm_ip_address', ip_address); ga.getXMLAnswer(function(response){ sessionStorage.setItem('scc', 'true');

    		var result = JSON.parse(response);
    		if(result.length >0){
    			var names = result.join(', ');
    			alert("servers: " +names);
    			g_form.clearValue('select_server');
    			sessionStorage.setItem('scp', 'false');
    		}
    		else{
    			sessionStorage.setItem('scp', 'true');
    		}
    		if(sessionStorage.getItem('scp') === 'true'){
    			g_form.submit();
    		}
    	});
    }
    });
    return false;
    

    }

  6. Assistant

    Your current script structure involves asynchronous processing (GlideAjax call to 'CheckOpStatus') to check the operational status of servers based on the IP address. Your requirement is to prevent form submission if there are operational servers found, showing an alert with their names. If no servers are found, you want to proceed with the form submission without requiring a second click on the submit button.

    The challenge you're encountering (needing two clicks to submit when no virtual server is found) results from the asynchronous nature of the GlideAjax call. The form submission proceeds (return false; is executed) before the Ajax response is received. When no virtual server is found, your code tries to submit the form again within the Ajax callback, but since the submission process has already been blocked (by return false;), it requires another click to initiate the submission again.

    One way to handle this is to restructure your approach to leverage client-side asynchronous handling more effectively, using a combination of flags and session storage to manage the form submission state across asynchronous checks.

    However, because GlideAjax is inherently asynchronous and your requirement involves halting form submission until the check completes, the exact behavior you desire (halt until response, then decide) is tricky within the onSubmit client script's synchronous flow without custom handling like below.

    Here's an adjusted approach to re-architect the script considering ServiceNow's client script execution environment:

    function onSubmit() {
        var isServerCheckComplete = sessionStorage.getItem('scc') === 'true';
        var isSubmissionAllowed = sessionStorage.getItem('scp') === 'true';
    
        // Reset session state for fresh operation
        function resetSessionState() {
            sessionStorage.removeItem('scc');
            sessionStorage.removeItem('scp');
        }
    
        // If server check is complete, decide based on whether submission is allowed
        if (isServerCheckComplete) {
            resetSessionState();  // Always clear session state after check
            return isSubmissionAllowed;  // Allow submission only if server check passed (no operational servers found)
        } else {
            // Perform the server check
            var selectServer = g_form.getValue('select_server');
            g_form.getReference('select_server', function(ref) {
                var ip_address = ref.ip_address;
                if (ip_address) {
                    var ga = new GlideAjax('CheckOpStatus');
                    ga.addParam('sysparm_name', 'getParentNames');
                    ga.addParam('sysparm_ip_address', ip_address);
                    ga.getXMLAnswer(function(response) {
                        var result = JSON.parse(response);
                        sessionStorage.setItem('scc', 'true');  // Mark server check as complete
    
                        if (result.length > 0) {
                            var names = result.join(', ');
                            alert("Operational servers found: " + names);
                            g_form.clearValue('select_server');
                            sessionStorage.setItem('scp', 'false');
                        } else {
                            sessionStorage.setItem('scp', 'true');
                            g_form.submit();  // Directly submit if no operational servers found
                        }
                    });
                }
            });
            return false;  // Initially prevent form submission to wait for Ajax response
        }
    }
    

    This script checks if the server operational status has already been validated. If not, it proceeds with the validation, and based on the validation result (i.e., operational servers are found or not), it either shows an alert and blocks submission or allows it. It leverages session storage to remember the state of validation and whether submission is allowed across the asynchronous callback.

    This solution aims to fulfill your requirement by structuring the asynchronous logic in a way that respects the synchronous onSubmit handler's constraints, allowing or blocking submission appropriately.

  7. User

    code is working as expected but in below code condition when it go for else, it takes 2 click to submit the form. please modify if else condition is execute it will only take 1 click to submit else { sessionStorage.setItem(‘scp’, ‘true’); g_form.submit();

  8. Assistant

    The challenge you're encountering arises from the asynchronous execution of the GlideAjax call, which doesn't complete before the form's default submission behavior (the first click). Your approach tries to bypass this by storing the state in sessionStorage and then, based on this stored state, deciding whether to submit the form again once the asynchronous call completes. However, because this check and state update occur too late in the form submission lifecycle, you end up needing an extra click to trigger the form submission check again and actually submit.

    One key issue with the pattern of putting g_form.submit(); inside the GlideAjax callback is that it doesn't interfere with the initial form submission event's default behavior; it merely attempts to programmatically submit the form after the initial submission event has already been canceled (return false;).

    A revised approach involves preventing form submission unless a certain condition is met (check completed and servers not found). When conditions are not met, we hold the submission, perform our checks, and then programmatically allow the submission if the condition resolves positively in our asynchronous callback. The critical part is to ensure that when we decide to allow submission (no servers found in your case), it does without requiring a second click.

    To solve the two-click issue properly, you might have to restructure how and when you prompt for submission, given the reactive nature of client scripts to user actions in ServiceNow. Unfortunately, due to how ServiceNow client scripts and GlideAjax work together, there's no direct and clean solution to perform an async check in onSubmit and then continue with submission without some form of user interaction when async operations are involved.

    However, here's an updated conceptual workaround that tries to minimize the need for user re-interaction:

    function onSubmit() {
        var asyncCheckCompleted = sessionStorage.getItem('asyncCheckCompleted') === 'true';
        var allowSubmission = sessionStorage.getItem('allowSubmission') === 'true';
        
        // Clear session storage to prevent unintended behavior on subsequent submissions
        function clearAsyncSessionItems() {
            sessionStorage.removeItem('asyncCheckCompleted');
            sessionStorage.removeItem('allowSubmission');
        }
    
        if (!asyncCheckCompleted) {
            // Perform the async check only if not done already
            checkServerStatus(function(shouldSubmit) {
                sessionStorage.setItem('asyncCheckCompleted', 'true');
                sessionStorage.setItem('allowSubmission', shouldSubmit.toString());
                if (shouldSubmit) {
                    g_form.clearMessages(); // Clear existing messages to avoid confusion
                    g_form.addInfoMessage("No operational servers found, submitting form...");
                    // Trick to allow client-side re-evaluation of onSubmit. This is not a standard approach but aims to meet your requirements.
                    setTimeout(function() {
                        g_form.save(); // Attempt to save (submit) the form again
                    }, 1000); // Delay to ensure user sees the message
                } else {
                    g_form.addErrorMessage("Operational servers found, cannot submit.");
                    clearAsyncSessionItems(); // Clear since we do not want to proceed
                }
            });
            return false; // Prevent form submission to wait for the async check
        } else {
            clearAsyncSessionItems(); // Ensure clean-up to avoid affecting future submissions
            return allowSubmission; // Proceed based on the async check outcome
        }
    }
    
    function checkServerStatus(callback) {
        var ip_address = g_form.getValue('select_server'); // Assuming this is how you get your IP address
        if (ip_address) {
            var ga = new GlideAjax('CheckOpStatus');
            ga.addParam('sysparm_name', 'getParentNames');
            ga.addParam('sysparm_ip_address', ip_address);
            ga.getXMLAnswer(function(response) {
                var result = JSON.parse(response);
                var names = result.join(', ');
                if (result.length > 0) {
                    alert("Operational servers found: " + names);
                    callback(false); // Do not allow submission
                } else {
                    callback(true); // Allow submission
                }
            });
        } else {
            // No IP address, callback based on your logic, assuming true (allow submission)
            callback(true);
        }
    }
    

    Please note:

    • Adjust the checkServerStatus function as per your actual implementation needs, especially how you retrieve and handle the ip_address.
    • This implementation introduces a slight delay to allow showing an info message before attempting to re-submit the form programmatically. Adjust the timing as you see fit.
    • This approach works around the limitation by effectively minimizing the undesired two-click behavior but doesn't completely eliminate the need for wise handling of asynchronous operations in the onSubmit event. It's a bit of a hack to reintroduce the form submission programmatically and should be used with understanding of the implications.