this didnt work in catalog client script, can you do it with script include and catalog client script, in servicenow
function onSubmit() {
//Type appropriate comment here, and begin script below
var descVariableName = 'u_description'; // Ensure this matches your variable name
code
// Get the value of the description variable
var descriptionValue = g_form.getValue(descVariableName);
// Check if the variable has a value and it does not already start with "PRE: "
if (descriptionValue && !descriptionValue.startsWith('FSP Service Request: ')) {
// Prefix the variable value with "PRE: "
g_form.setValue(descVariableName, 'FSP Service Request: ' + descriptionValue);
}
}
Assistant
To implement the required functionality in ServiceNow using both Script Include and Catalog Client Script, you can follow these steps:
Step 1: Create a Script Include
Navigate to System Definition > Script Includes.
Click on New.
Fill in the fields as follows:
Name: DescriptionHandler
API Name: DescriptionHandler (or as your preference)
Application: Choose the appropriate application.
Accessible from: Set it to All application scopes or a specific one based on your needs.
Script: Use the following code:
javascript
var DescriptionHandler = Class.create();
DescriptionHandler.prototype = {
initialize: function() {},
/**
* Prepends a specific prefix to the provided description if it doesn't already have it.
* @param {string} description Value of the description variable.
* @returns {string} New description with the prefix, if applicable.
*/
addPrefix: function(description) {
var prefix = 'FSP Service Request: ';
if (description && !description.startsWith(prefix)) {
return prefix + description;
}
return description;
},
type: 'DescriptionHandler'
};
Step 2: Create a Catalog Client Script
Navigate to Service Catalog > Catalog Definitions > Client Scripts.
Click on New.
Fill in the fields as follows:
Name: Add Description Prefix
Table: Choose the relevant catalog item or keep it as global if needed.
UI Type: Select All.
Script: Use the following code:
javascript
function onSubmit() {
var descVariableName = 'u_description'; // Ensure this matches your variable name
// Get the value of the description variable
var descriptionValue = g_form.getValue(descVariableName);
// Create an instance of the Script Include
var handler = new DescriptionHandler();
// Use the function from the Script Include to get the new description
var newDescription = handler.addPrefix(descriptionValue);
// Set the value back to the form
g_form.setValue(descVariableName, newDescription);
}
Summary
Script Include: DescriptionHandler contains a method addPrefix that checks the description and prepends the prefix if needed.
Catalog Client Script: The client script Add Description Prefix uses the script include to modify the description value upon the form submission.
By following these steps, you'll ensure that the description gets the appropriate prefix only when it doesn't already have it. Make sure to test the functionality in a sub-production instance before going live.
User
can we have script inlcude in this format
Assistant
Certainly! If you'd like the Script Include in a more compact or alternative format, while still maintaining its functionality, here is a revised version that adheres to a more straightforward structure.
Revised Script Include
Navigate to System Definition > Script Includes.
Click on New.
Fill in the fields as follows:
Name: DescriptionHandler
Application: Choose the appropriate application.
Script: Use the following code:
javascript
var DescriptionHandler = Class.create();
DescriptionHandler.prototype = {
initialize: function() {},
addPrefix: function(description) {
// Define the prefix
const prefix = 'FSP Service Request: ';
// Check if description is not empty and does not start with the prefix
return description && !description.startsWith(prefix) ? prefix + description : description;
},
type: 'DescriptionHandler'
};
Explanation of the Script Include Code
initialize(): This is the constructor function and can be omitted if no initialization is needed.
addPrefix(description): This method takes a description as input and checks if it starts with the predefined prefix. If it does not, it prefixes the description; otherwise, it returns the original description.
Updated Catalog Client Script
You can use the previous client script without change as it is already set up to call the addPrefix function:
javascript
function onSubmit() {
var descVariableName = 'u_description'; // Ensure this matches your variable name
// Get the value of the description variable
var descriptionValue = g_form.getValue(descVariableName);
// Create an instance of the Script Include
var handler = new DescriptionHandler();
// Use the function from the Script Include to get the new description
var newDescription = handler.addPrefix(descriptionValue);
// Set the value back to the form
g_form.setValue(descVariableName, newDescription);
}
Summary
The revised Script Include structure keeps it simple and efficient, while still complying with your request for a format change. The functionality of checking for the prefix and modifying the description remains intact.
Make sure to test the implementation in your ServiceNow instance before deploying it widely.
User
format of old working one script include is
getAssignmentGroup: function() {
var assignList = [];
var groupName = new GlideRecord("sys_user_group");
groupName.addEncodedQuery("nameINSALESHUB PLUS SUPPORT,SALESPRO PLUS SUPPORT,SALES LEAD PLUS SUPPORT,GROWTH ORDER SUPPORT,PFNA COMMERICAL RELEASE SUPPORT");
groupName.query();
while (groupName.next()) {
assignList.push(groupName.getValue("sys_id"));
}
return 'sys_idIN' + assignList;
Assistant
Thank you for the clarification on the format you're looking for. Below is the revised Script Include structured similarly to your example, ensuring it fits your desired pattern.
Script Include Using Your Format
Navigate to System Definition > Script Includes.
Click on New.
Fill in the fields as follows:
Name: DescriptionHandler
Application: Choose the appropriate application.
Script: Use the following code:
javascript
var DescriptionHandler = Class.create();
DescriptionHandler.prototype = {
initialize: function() {},
addPrefix: function(description) {
if (description && !description.startsWith('FSP Service Request: ')) {
return 'FSP Service Request: ' + description;
}
return description;
},
type: 'DescriptionHandler'
};
Explanation of the Revised Script Include
initialize(): This function is empty as no initial setup is needed.
addPrefix(description):
The function checks whether description is not empty and doesn't start with 'FSP Service Request: '.
If conditions are met, it prefixes the description with 'FSP Service Request: '.
If not, it simply returns the original description.
Updated Catalog Client Script
Here’s the corresponding Catalog Client Script which does not need to change. It will work seamlessly with the above Script Include:
javascript
function onSubmit() {
var descVariableName = 'u_description'; // Ensure this matches your variable name
// Get the value of the description variable
var descriptionValue = g_form.getValue(descVariableName);
// Create an instance of the Script Include
var handler = new DescriptionHandler();
// Use the function from the Script Include to get the new description
var newDescription = handler.addPrefix(descriptionValue);
// Set the value back to the form
g_form.setValue(descVariableName, newDescription);
}
Summary
This implementation matches the format you provided while maintaining the functional requirements. The addPrefix is structured clearly, following your example while ensuring clean and manageable code.
Feel free to test it in your ServiceNow instance and make further adjustments as needed!
User
this shows on catalog form
Assistant
To prevent the Script Include from showing on the Catalog form and ensure that it's only used for logic processing, you'll want to make sure that the Script Include is properly structured and that it doesn’t inadvertently expose itself to the client-side.
Steps to Ensure Correct Implementation
Ensure Proper Access Level: Set the Script Include to be Client callable if it’s intended to be invoked from client scripts. If it’s only to be used from other server-side scripts, make sure to keep that option unchecked.
Use the Right Structure: Follow the structure you provided previously, keeping in mind that scripts need to be written cleanly and executed only from where they are intended.
Updated Script Include
Here's an improved version based on your requirements:
javascript
var DescriptionHandler = Class.create();
DescriptionHandler.prototype = {
initialize: function() {},
/**
* Adds a prefix to the provided description if it does not already have it.
* @param {string} description - The initial description value.
* @return {string} - The new description with the prefix if applicable.
*/
addPrefix: function(description) {
// Define the prefix
var prefix = 'FSP Service Request: ';
// Check if description exists and does not start with the prefix
if (description && !description.startsWith(prefix)) {
return prefix + description;
}
return description;
},
type: 'DescriptionHandler'
};
Catalog Client Script
Using the following client script is crucial to ensure that it is only ever processed on the client side, and doesn’t interfere with displaying values on the catalog form:
javascript
User
this shows on catalog form
onSubmit script error: ReferenceError: pfnaVariableQualifier is not defined:
Assistant
The error "ReferenceError: pfnaVariableQualifier is not defined" indicates that there is likely an attempt to reference a variable that hasn’t been properly declared or initialized in your script. This could happen for a few reasons, usually related to instance-specific or context-specific variables in your ServiceNow environment.
Steps to Resolve the Error
1. Identify the Source of the Error:
Make sure that you are not trying to access a variable named pfnaVariableQualifier anywhere in your code without defining it first. If this is intended to be a form variable, ensure that it actually exists on the catalog item form you're working with.
2. Review Related Scripts:
Look at the related Client Scripts, business rules, or any other logic that may be trying to access pfnaVariableQualifier. The variable should be a valid catalog item variable name prefixed with its scope or identifier (u_ for custom variables).
3. Example Correct Usage:
Here’s how you might use a variable in a catalog client script without running into undeclared reference issues.
Example of Correct Usage in Client Script:
javascript
function onSubmit() {
// Ensure your variable names are correct and match those in the form
var descVariableName = 'u_description'; // Ensure this matches your variable name
var pfnaVariableQualifier = g_form.getValue('pfna_variable_name'); // Use the correct variable name here
// Get the value of the description variable
var descriptionValue = g_form.getValue(descVariableName);
// Create an instance of the Script Include
var handler = new DescriptionHandler();
// Use the function from the Script Include to get a new description
var newDescription = handler.addPrefix(descriptionValue);
// Set the value back to the form
g_form.setValue(descVariableName, newDescription);
// Check if pfnaVariableQualifier is used later on
if (pfnaVariableQualifier) {
// Perform some action with pfnaVariableQualifier
console.log('Variable is defined: ' + pfnaVariableQualifier);
} else {
console.log('pfnaVariableQualifier is NOT defined.');
}
}
User
where is the function name
Assistant
I see the confusion—thank you for your patience! The client script function that you need for handling the form submission is the onSubmit function. This function is invoked automatically when the user attempts to submit the catalog form.
Here's a clearer breakdown of how to structure your catalog client script with comments to indicate the function definition:
Catalog Client Script
javascript
function onSubmit() {
// Variable name defined in the catalog item (ensure it's correct)
var descVariableName = 'u_description'; // The variable name for description
var pfnaVariableName = 'u_pfna_variable'; // Replace with actual variable name if necessary
// Get the value of the description variable
var descriptionValue = g_form.getValue(descVariableName);
// Optionally retrieve the value of another variable if needed
var pfnaVariableQualifier = g_form.getValue(pfnaVariableName); // Get specific variable
// Create an instance of the Script Include
var handler = new DescriptionHandler();
// Use the function from the Script Include to get the new description
var newDescription = handler.addPrefix(descriptionValue);
// Set the modified description back to the form
g_form.setValue(descVariableName, newDescription);
// Example of using the pfnaVariableQualifier
if (pfnaVariableQualifier) {
console.log('pfnaVariableQualifier is defined: ' + pfnaVariableQualifier);
} else {
console.log('pfnaVariableQualifier is NOT defined.');
}
// Returning true to allow the form submission to proceed
return true; // Ensure to allow the form submission
}
Key Points:
User
i have this script include with name. : pfnaVariableQualifier
addPrefix: function(description) {
if (description && !description.startsWith('FSP Service Request: ')) {
return 'FSP Service Request: ' + description;
}
return description;
},
client script:
Assistant
Certainly! To integrate the provided script include pfnaVariableQualifier and use its addPrefix function in a Catalog Client Script, we can follow a structured approach. Below is how you might implement both the Script Include and the Catalog Client Script.
Step 1: Script Include
Assuming your Script Include is named pfnaVariableQualifier, it would look like this. Make sure you check the "Client Callable" checkbox if you intend to call it from the client-side.
Script Include Code:
javascript
var pfnaVariableQualifier = Class.create();
pfnaVariableQualifier.prototype = {
initialize: function() {},
/**
* Adds the prefix 'FSP Service Request: ' to the description if it doesn't already have it.
* @param {string} description - The description to possibly modify.
* @return {string} - The modified description with the prefix.
*/
addPrefix: function(description) {
if (description && !description.startsWith('FSP Service Request: ')) {
return 'FSP Service Request: ' + description;
}
return description;
},
type: 'pfnaVariableQualifier'
};
Step 2: Catalog Client Script
Next, your Catalog Client Script will use this Script Include to modify the description upon form submission.
Client Script Code:
Navigate to Service Catalog > Catalog Definitions > Client Scripts.
Click on New.
Fill in the following details in the Client Script form:
Name: Add Description Prefix
Table: Template (or your specific catalog item)
UI Type: All
Script:
javascript
User
please provide the client script in this format also:
var id = g_form.getValue("app_name");
var gaformAjax = new GlideAjax("pfnaAjax");
gaformAjax.addParam("sysparm_name", "getServiceOff");
gaformAjax.addParam("sysparm_id", id);
gaformAjax.getXML(usrCallback);
code
function usrCallback(response) {
var answer = response.responseXML.documentElement.getAttribute('answer');
g_form.setValue("service_offering", answer);
}
Assistant
Sure! If you want to structure your Catalog Client Script similarly to the format you provided with the use of GlideAjax, the code will need to utilize the GlideAjax object to call the Script Include. Below, I'll create a Catalog Client Script that prepends the prefix "FSP Service Request: " to the description variable using GlideAjax to handle any logic in the server-side Script Include.
Revised Catalog Client Script
Here's how you can structure your Catalog Client Script to utilize GlideAjax and the pfnaVariableQualifier Script Include:
javascript
function onSubmit() {
var descVariableName = 'u_description'; // Ensure this matches the variable name on your form
// Get the current value of the description variable
var descriptionValue = g_form.getValue(descVariableName);
// Create a GlideAjax object with the Script Include name
var ga = new GlideAjax('pfnaVariableQualifier');
ga.addParam('sysparm_name', 'addPrefix'); // The function in Script Include to call
ga.addParam('sysparm_description', descriptionValue); // Pass the current description
// Send the request and set a callback function to handle the response
ga.getXML(callback);
function callback(response) {
// Retrieve the answer from the response
var newDescription = response.responseXML.documentElement.getAttribute('answer');
// Set the modified description back to the form
g_form.setValue(descVariableName, newDescription);
}
// Allow form submission to proceed
return true;
}
Key Points Explained:
Variable Definition:
var descVariableName = 'u_description'; ensures you're using the correct variable name that is actually present in the catalog item form.
User
i create a new catalog client script but not working on esc portal, works only on test portal, please return true or false, return true only if value is set in description then submit the form.
function onSubmit() {
//Type appropriate comment here, and begin script below
var descriptionValue = g_form.getValue('u_description');
code
// Check if the variable has a value and it does not already start with "PRE: "
if (descriptionValue && !descriptionValue.startsWith('FSP Service Request: ')) {
// Prefix the variable value with "PRE: "
g_form.setValue('u_description', 'FSP Service Request: ' + descriptionValue);
}
}
Assistant
To ensure your Catalog Client Script works properly on the Service Portal (ESC Portal) and returns true or false based on the conditions you've specified, you need to make a few adjustments to your onSubmit function. Specifically, you want to ensure that you only submit the form if the description has been set with the desired prefix.
Revised Catalog Client Script
Here’s how you can structure your onSubmit function:
javascript
function onSubmit() {
// Get the current value of the description variable
var descriptionValue = g_form.getValue('u_description');
// Check if the variable has a value and does not already start with "FSP Service Request: "
if (descriptionValue && !descriptionValue.startsWith('FSP Service Request: ')) {
// Prefix the variable value with "FSP Service Request: "
g_form.setValue('u_description', 'FSP Service Request: ' + descriptionValue);
}
// Check if the updated description variable has the prefix
var updatedDescriptionValue = g_form.getValue('u_description');
if (updatedDescriptionValue.startsWith('FSP Service Request: ')) {
// Return true to allow the form to be submitted
return true;
} else {
// Return false to prevent the form from submitting
alert('Description must be set.');
return false;
}
}
Key Adjustments Made
Updated Prefix Check:
The string checking and prefixing logic now correctly uses FSP Service Request: to ensure that the correct text is set.
Submission Control:
After potentially modifying the description, the script checks whether the u_description starts with the desired prefix.
If the prefix is present, it returns , allowing the form to go through. If not, it alerts the user and returns to prevent form submission.
User
working on test portal only, but not on esc portal,
Assistant
If the Catalog Client Script is working in the Test Portal but not in the ESC Portal (Service Portal), it could be due to several factors related to the way the Service Portal handles client scripts differently from the Classic UI. Let's troubleshoot a few common issues and provide a tailored solution that specifically addresses those:
Steps to Troubleshoot and Resolve
Script Debugging:
Use console.log() to debug and check if the script is being executed as expected on the Service Portal. Since alert dialogs might not show in the Service Portal, using console.log() will help identify where the script may be failing.
Add logging right at the beginning and throughout the script to confirm execution flow.
Use of g_form:
Make sure the variable name used in g_form.getValue and g_form.setValue matches the variable IDs in the Service Portal. Sometimes, u_ field names can differ based on context.
You may want to check if the variable is available on the form or if it's being manipulated some other way.
Change Event:
Ensure that your client script is set to run on the appropriate event. Double-check that the script type is "onSubmit" in the Service Portal context.
Scope:
Make sure the client script is in the correct application scope and that there are no permission issues.
Revised Client Script for Service Portal
Below is an updated version of your client script that incorporates debugging and adjusted logic for Service Portal:
javascript
User
make it onchange one time for testing only
Assistant
If you'd like to modify the script so that it runs on the onChange event of the description variable (useful for testing), you can set it up like this. The following script will execute whenever the description field changes, allowing you to see if the prefixing logic works correctly without needing to submit the form.
Revised OnChange Client Script
Create a New Catalog Client Script:
Go to Service Catalog > Catalog Definitions > Client Scripts.
Click on New and set the following fields:
Name: Add Description Prefix (OnChange Test)
Table: Select the relevant catalog item.
UI Type: All
Type: OnChange
Field Name: u_description (the variable you want to monitor).
Use the Following Script:
javascript
// This function runs when the 'u_description' field changes
function onChange(control, oldValue, newValue) {
// Check if the new value should have the prefix
if (newValue && !newValue.startsWith('FSP Service Request: ')) {
// Prefix the variable value with "FSP Service Request: "
var prefixedValue = 'FSP Service Request: ' + newValue;
g_form.setValue('u_description', prefixedValue); // Set the new value
console.log('Description updated to:', prefixedValue); // Debugging log
} else {
console.log('No changes made. Current description:', newValue); // Debugging log
}
}
Key Elements of the OnChange Script
Function Trigger:
The function is triggered whenever the u_description field changes, providing immediate feedback as the user types or modifies the description.
Value Check and Prefixing:
The script checks whether the new value is not empty and does not already include the prefix before adding it.
Setting the Value:
If the description does not already start with the prefix, it updates the field to include it.
Console Logging:
Debugging logs are present to track when the description is changed and what the resulting new value is.
Conclusion
With this onChange client script, you can test the functionality quickly without needing to submit the form, providing a live update as the user modifies the description. Make sure to monitor the browser's console to track the changes being logged. After testing, you can implement the logic back into an onSubmit function if desired or keep it as an onChange event for ongoing refinement.
User
working now, make this as on submit not
Assistant
Great to hear that the onChange script is working! Now, let's convert this back into an onSubmit event so that the prefixing logic happens when the user attempts to submit the form, rather than when the description field changes.
Catalog Client Script for OnSubmit
Here’s how you can set up your onSubmit client script to ensure it checks and updates the description before allowing the form submission:
Create a New Catalog Client Script:
Go to Service Catalog > Catalog Definitions > Client Scripts.
Click on New and set the following fields:
Name: Add Description Prefix (OnSubmit)
Table: Select the relevant catalog item.
UI Type: All
Type: OnSubmit
Use the Following Script:
javascript
function onSubmit() {
// Get the current value of the description variable
var descriptionValue = g_form.getValue('u_description');
// Check if the variable has a value and it does not already start with "FSP Service Request: "
if (descriptionValue && !descriptionValue.startsWith('FSP Service Request: ')) {
// Prefix the variable value with "FSP Service Request: "
g_form.setValue('u_description', 'FSP Service Request: ' + descriptionValue);
console.log('Description updated to:', g_form.getValue('u_description')); // Debugging log
}
// Recheck to see if the description has the prefix now
var updatedDescriptionValue = g_form.getValue('u_description');
// Allow submission only if the description has the prefix
if (updatedDescriptionValue.startsWith('FSP Service Request: ')) {
console.log('Form can be submitted.'); // Debugging log
return true; // Allow the form to be submitted
} else {
console.log('Description must start with "FSP Service Request: ". Form submission aborted.'); // Debugging log
g_form.addErrorMessage('Description must start with "FSP Service Request: ".'); // Show error message
return false; // Prevent submission
}
}
Not yet included in a published release.
function onSubmit() {
var descVariableName = 'u_description'; // Ensure this matches your variable name
// Get the value of the description variable
var descriptionValue = g_form.getValue(descVariableName);
// Create an instance of the Script Include
var handler = new DescriptionHandler();
// Use the function from the Script Include to get the new description
var newDescription = handler.addPrefix(descriptionValue);
// Set the value back to the form
g_form.setValue(descVariableName, newDescription);
}
Key Points to Consider
Visibility on Catalog Form: By default, a Script Include does not show on the form. If you are seeing unexpected behavior, double-check where it is being called from. A Script Include should only execute when explicitly invoked.
Testing: Ensure you test this setup by creating a new service catalog request and observing the behavior of the description field during the submission process.
Debugging: If there are issues, use the Script Debugger (or simply gs.info() for server-side logging) to trace where things might be going wrong. You can also use alert() or console.log() for client-side debugging.
Conclusion
This setup should work properly without displaying the script include on the catalog form. It adheres to your format requirements and encapsulates the business logic within the Script Include while being leveraged through the catalog client script. If you continue to experience issues or have specific error messages, please share them for more targeted assistance.
Key Considerations
Variable Names:
Double-check the existence of the variable pfna_variable_name on your catalog form and ensure it is spelled correctly (case-sensitive).
Ensuring Variables are Loaded:
If pfnaVariableQualifier is supposed to be a variable from the catalog item form, make sure that the variable exists, and you are using the correct method (g_form.getValue('variable_name')) to retrieve its value.
Debugging:
Use console.log() to debug and track which variables are successfully being retrieved and if any variables are undefined.
Fallback Handling:
If you're still unsure about references, you can use conditional checks to see if the variable is defined before using it, which can prevent runtime errors.
Conclusion
This structure ensures you’re using the correct variable names and helping avoid the ReferenceError you encountered. If the problem persists, review all sections of the client script where you might call or rely on undefined variables and ensure they are correctly initialized.
Function Declaration:
The function name is onSubmit, which is important as that is automatically triggered by the ServiceNow system when the form is submitted.
Use of Variable Names:
Make sure that all variable names used (u_description and u_pfna_variable in this example) match exactly what is defined on your Service Catalog item. It's crucial to use the correct names to avoid ReferenceError.
Logging:
I included logging statements to help track whether a variable is defined and what its value is. This is useful for debugging.
Return Statement:
The return true; at the end of the function ensures that the form submission is allowed to proceed. If you want to prevent submission under certain conditions, you could use return false;.
Database of the Script Include
As noted earlier, here is the Script Include you’ll also use, which does not need a change in function call structure:
javascript
var DescriptionHandler = Class.create();
DescriptionHandler.prototype = {
initialize: function() {},
/**
* Adds a prefix to the provided description if it does not already have it.
* @param {string} description - The initial description value.
* @return {string} - The new description with the prefix if applicable.
*/
addPrefix: function(description) {
var prefix = 'FSP Service Request: ';
if (description && !description.startsWith(prefix)) {
return prefix + description;
}
return description;
},
type: 'DescriptionHandler'
};
Conclusion
You have now a clearly defined onSubmit function within the context of a catalog client script that operates in tandem with your DescriptionHandler Script Include. Make sure to test everything properly within your ServiceNow environment to ensure it behaves as expected when a user submits the form.
function onSubmit() {
// The variable name should match your catalog variable
var descVariableName = 'u_description'; // Ensure this matches the actual variable name on your form
// Get the current value of the description variable
var descriptionValue = g_form.getValue(descVariableName);
// Create an instance of the Script Include
var handler = new pfnaVariableQualifier();
// Use the function from the Script Include to get a new description
var newDescription = handler.addPrefix(descriptionValue);
// Set the modified description back to the form
g_form.setValue(descVariableName, newDescription);
// Allow form submission to proceed
return true;
}
Key Points:
Function Declaration: The onSubmit function is defined as the entry point when the form is submitted.
Variable Naming: The variable descVariableName must be adjusted to match the name of the description variable in your catalog item (ensure it starts with u_ if it's a custom variable).
Creating an Instance of the Script Include: The line var handler = new pfnaVariableQualifier(); creates an instance of your Script Include so you can call the addPrefix method.
Modifying the Value: The g_form.setValue(descVariableName, newDescription); line updates the description field with the new value, whether it has been modified or not.
Return Statement: return true; at the end is essential to allow the form to submit.
Conclusion
This setup allows for a seamless interaction between the client-side form handling and the server-side logic encapsulated within your Script Include. Test this configuration in your ServiceNow instance to verify that it behaves as expected, allowing the description to automatically receive the specified prefix upon submission. Feel free to reach out for further adjustments or questions!
Get Current Value:
var descriptionValue = g_form.getValue(descVariableName); retrieves the current text of the description field to pass it to the server-side logic.
GlideAjax Setup:
var ga = new GlideAjax('pfnaVariableQualifier'); initializes the GlideAjax object with the name of the Script Include you want to invoke.
ga.addParam('sysparm_name', 'addPrefix'); specifies which function in the Script Include to call when the request is made.
ga.addParam('sysparm_description', descriptionValue); sends the value of the description variable as a parameter to the Script Include.
Response Handling:
The callback function is defined to process the response once the server action completes.
var newDescription = response.responseXML.documentElement.getAttribute('answer'); captures the returned value from the Script Include.
Updating the Form Value:
g_form.setValue(descVariableName, newDescription); sets the new description (with the prefix) back on the catalog form.
Form Submission:
return true; ensures that the form submits after handling the necessary logic.
Assumed Script Include Logic
For this to work, your pfnaVariableQualifier Script Include must be capable of handling the addPrefix method, retrieving the sysparm_description, and returning the modified string. Here’s a sample modification to the Script Include:
javascript
var pfnaVariableQualifier = Class.create();
pfnaVariableQualifier.prototype = {
initialize: function() {},
/**
* Adds the prefix 'FSP Service Request: ' to the description if it doesn't already have it.
* @returns {string} - The modified description.
*/
addPrefix: function() {
// Retrieve the parameter passed from GlideAjax
var description = this.getParameter('sysparm_description');
// Check if the description exists and doesn't start with the prefix
if (description && !description.startsWith('FSP Service Request: ')) {
return 'FSP Service Request: ' + description;
}
return description;
},
type: 'pfnaVariableQualifier'
};
Conclusion
With this setup, your catalog client script utilizes GlideAjax to communicate effectively with the server-side Script Include, achieving the intended prefix functionality for the description variable in a structured format similar to what you provided. Be sure to test it thoroughly in your instance to confirm that everything works as expected!
true
false
User Feedback:
An alert is included to inform the user if the description does not meet the criteria (i.e., it must begin with the prefix). This feedback helps users correct their input.
Important Considerations
Form Submission Behavior in Service Portal: Sometimes, there can be behavioral differences between the Service Portal and the Classic UI. Ensure that all associated form variables and any other validations work correctly across both environments.
Testing: Make sure to thoroughly test this in both the Service Portal and the standard Service Catalog environments. Check console errors using the browser's Developer Tools if the script does not behave as expected.
Conclusion
With these changes, your Catalog Client Script will now work effectively on the ESC Portal, ensuring the form is submitted only when the description is correctly prefixed, providing users with an actionable message if their input doesn't meet the criteria.
function onSubmit() {
// Debugging: log to console
console.log('onSubmit function called');
// Get the current value of the description variable
var descriptionValue = g_form.getValue('u_description');
console.log('Current description value:', descriptionValue);
// Check if the variable has a value and does not already start with "FSP Service Request: "
if (descriptionValue && !descriptionValue.startsWith('FSP Service Request: ')) {
// Prefix the variable value with "FSP Service Request: "
g_form.setValue('u_description', 'FSP Service Request: ' + descriptionValue);
console.log('Description updated to:', g_form.getValue('u_description'));
}
// Get the updated description value
var updatedDescriptionValue = g_form.getValue('u_description');
console.log('Updated description value:', updatedDescriptionValue);
// Check if the updated description variable has the prefix
if (updatedDescriptionValue.startsWith('FSP Service Request: ')) {
console.log('Form will be submitted.');
return true; // Submit the form
} else {
console.log('Description must be set properly. Aborting submission.');
// Optionally you can show a message in the Service Portal
g_form.addErrorMessage('Description must start with "FSP Service Request: ".');
return false; // Prevent submission
}
}
Key Changes & Additions
Debugging with console.log:
Logs added to provide insights into the flow of execution and to verify variable values at each step.
Error Messages:
g_form.addErrorMessage() is used instead of an alert. This is more user-friendly in the Service Portal, providing visible feedback to the user without disrupting the UI.
Confirmation of Descriptive Prefix:
The condition checks that the description indeed gets updated and begins with the expected prefix before allowing submission.
Conclusion
This setup should help troubleshoot why the script isn't working on the ESC Portal, checking for correct variable values and ensuring an appropriate submission condition. Test this revised script in the Service Portal and observe the console logs for any discrepancies or additional insights that may arise. If you continue facing issues, please provide any errors you're seeing in the browser console, as that would greatly help in diagnosing the problem further.
Key Elements of the OnSubmit Script
Value Retrieval:
It retrieves the current value of u_description using g_form.getValue.
Condition Checking:
It checks to see if the description is not empty and does not already include the prefix before updating it.
Setting the New Value:
If necessary, the description is updated with the prefix using g_form.setValue.
Final Submission Check:
It checks the updated value to see if the prefix is present before allowing the form to submit.
If the prefix is there, it returns true and logs that the form can be submitted.
If not, it shows a user-friendly error message and returns false to prevent submission.
Debugging Logs:
The logs help trace the functionality through the console, making it easier to debug.
Conclusion
This script now manages the modification and validation of the description variable during the submission process. The form will only be submitted if the description starts with the specified prefix. Make sure to test this in your Service Portal to confirm its functionality and usability. If you have any further requirements or adjustments, feel free to ask!