servicenow I want to auto-populate the Company and Cost center code of the "requested…
- User
servicenow
I want to auto-populate the Company and Cost center code of the "requested for" user without writing client script/ UI policies. I want update on the variable level. I tried by providing the default value as "javascript:gs.getUser().getCompanyID();". But, I'm just getting the SysID of the Company. Tried by giving alternative value as well, like CompanyName.. but not working
Can anybody please help me to get the correct value of the Company and cost center code together. As I don't have idea, which backend value to be provided under "Default"
Example., Netherland - NL
- Assistant
If you want to auto-populate the Company and Cost Center code fields for the "requested for" user directly in the variable level without using client scripts or UI policies, you can use the 'Default Value' field. However, achieving this directly within the 'Default Value' can be complex and sometimes limited in functionality as it supports only specific types of scripts.
Here are some steps and tips to achieve this:
Step 1: Understanding the
default valuelimitationThe 'Default Value' field can take JavaScript but only very basic JavaScript expressions are supported.
Step 2: Using the GlideRecord method
You can use the
glideRecordmethod to fetch the required values from the corresponding tables.Example:
However, the syntax you are trying to use is not supported directly in the
Default Value. Instead, you can use a business rule or a combination of dictionary overrides and default values set through a script include or similar means.Alternate Approach:
Given the limitations in the Default Values, here’s a workaround that does not rely on client scripts or UI Policies:
-
Business Rule:
- Create a Business Rule that runs on insert for the table where the record is being created.
- In the Business Rule, fetch the Company and Cost Center code based on the "requested for" user and set it to your variables.
(function executeRule(current, previous /*null when async*/) { var userRecord = new GlideRecord('sys_user'); if (userRecord.get(current.requested_for)) { current.company = userRecord.company; // Assuming 'company' is a reference field // To get Cost Center Code: var costCenter = new GlideRecord('cmn_cost_center'); if (costCenter.get(userRecord.cost_center)) { current.u_cost_center_code = costCenter.code; // Assuming 'u_cost_center_code' is the Custom field on your table } } })(current, previous); -
Script Include:
- You can create a Script Include that fetches these details based on the "requested for" user.
var UserDetails = Class.create(); UserDetails.prototype = { initialize: function() { }, getCompanyAndCostCenter: function(userId) { var result = {}; var userRecord = new GlideRecord('sys_user'); if (userRecord.get(userId)) { result.company = userRecord.getDisplayValue('company'); var costCenter = new GlideRecord('cmn_cost_center'); if (costCenter.get(userRecord.cost_center)) { result.costCenterCode = costCenter.code; } } return result; }, type: 'UserDetails' }; -
Example GlideForm - (Optional for synchronous loading):
- If your form still needs dynamic loading, you can use Async Business Rules which update the fields even after initial load directly in backend without user visibility.
Remember: These solutions assume that the fields in your form are writable by the business rule or the script.
Conclusion:
Achieving this directly with the Default Value property has limitations and often requires a more indirect approach, such as using Business Rules, Script Includes, or Dictionary Overrides in combination with server-side scripts.
If you must get these values on the client side without writing custom scripts, you might have to reconsider your constraints or look into custom workflow actions that populate these fields upon form submission.
It’s essential to test thoroughly and ensure the Business Rules or Script Includes are executed only when necessary, as they could affect performance if not managed properly.
-
- User
i need to do it without script
- Assistant
If you're constrained to achieve this without using scripts (client scripts, business rules, or script includes) and want to set default values for the "Company" and "Cost Center" based on the "requested for" user, you'll need to leverage existing ServiceNow configurations as much as possible. However, note that this significantly restricts your ability to dynamically retrieve and set these values.
You can utilize the Data Lookups and Dictionary attributes creatively. However, this will have limitations and might not fulfill all dynamic requirements.
Using Data Lookups:
Data Lookups in ServiceNow allow you to set values based on certain conditions in the form.
-
Create Data Lookup Definitions:
-
Go to System Policy > Rules > Data Lookup Definitions and create a new definition.
- Table: Requested table (like
sc_req_item) - Condition: Criteria to match the "requested for" user.
- Table: Requested table (like
-
Map Field Values:
- Define the fields you want to set based on the conditions.
- From Field: User
- To Field: Company
- From Field: User
- To Field: Cost Center (you would need appropriate fields)
- Define the fields you want to set based on the conditions.
-
-
Create Data Lookup Rules:
- Go to System Policy > Rules > Data Lookup Rules.
- Create a new rule associated with the Data Lookup Definition you previously created.
This way, you can use data lookup to map your values based on conditions.
Using Dictionary Attributes/Data Policies:
-
Default Values Based on Related Records:
- For directly setting default values in ServiceNow, you often have to predefine these values statically or use dictionary attributes for reference fields.
- If your "Company" and "Cost Center" are reference fields, ensure they are correctly linked to your user records.
-
Auto-fill with Dictionary Defaults (Field Definition):
- Go to System Definition > Dictionary and select your field.
- Here, you can set static default values if this fits your use case.
Example for Setting Static Default Values:
If you have static default companies and cost centers based on the location of users:
-
Using Field Mapping in User Record:
- Ensure each user record has the corresponding company and cost center filled appropriately (if not dynamically linked).
-
Default Values in Catalog Item Fields:
- For
Variablesection, utilize reference qualifiers if necessary:- Example: For Company Field →
javascript:gs.getUser().getCompanyID(); - This only fills the SysID but references can show display values.
- Example: For Company Field →
// Example in Default Value for Reference Fields javascript:var u = gs.getUser(); var c = new GlideRecord('core_company'); c.get(u.getCompanyID()); c.name; - For
-
Using Reference Qualifiers for User-Specific Defaults:
- Go to Maintain Items > Select your catalog item > open the variable.
- Set the reference qualifier for the "Company" and "Cost Center" to dynamically filter based on the current user's predefined associations.
// Reference Qualifier for displaying Company based on user javascript: 'company=' + current.sys_id;
Example using Related Lists in User Records:
-
Link 'Cost Center' to User Table Directly:
- Ensure each user has attributes directly related to Cost Center in their user record through related lists/entries.
-
Use Auto-Populate Features in Variable Setup:
- Use the default value features connected to
cmn_cost_centertable attributes assuming they are preset per user config in ServiceNow.
- Use the default value features connected to
// In Default Value or via Reference Qualifiers: javascript:var user = gs.getUser().id; var usr = new GlideRecord('sys_user'); usr.get(user); var costCenter = usr.cost_center.code; costCenter;Catalog Item and Attached Functions:
- For Service Catalog Items, ensure to use variable set appropriately.
- Creative use of workflow attached (but not direct scripts) to dynamically reason through user input.
Conclusion:
ServiceNow inherently limits non-script-based methods for dynamic default values. However, by creatively using Data Lookups, Dictionary Attributes, and Reference Qualifiers, you can achieve a level of automatic population with certain static constraints.
If business requirements change or the need for more dynamic assignments persists, revisiting script-based solutions would be optimal.
-
- User
Object ID from cloud resource able not available for Pivot type report in column or in row?
any reason ? how to make it available ?
- Assistant
In ServiceNow, if you're trying to create a pivot table report and you notice that the "Object ID" from a cloud resource table (or any specific field from a custom or standard table) is not available in the column or row options, there could be several reasons for this. Here are some common reasons and steps to potentially resolve the issue:
Common Reasons:
-
Field Missing from the Table Configuration:
- The "Object ID" field might not be configured properly in the table configuration or might not be active.
-
Field Type Limitations:
- Some field types may not be suitable for row/column categorization in pivot tables. Typically, reference fields, choice fields, and string fields are preferable.
-
Permissions Issues:
- You might not have the appropriate permissions to access or report on this field.
-
Data Source Configuration:
- The data source or report configuration might not include this field due to filtering or definition constraints.
Steps to Resolve:
-
Check the Field Configuration:
- Go to System Definition > Tables and search for the relevant table.
- Check the "Object ID" field to ensure it is correctly configured and active.
- Ensure it is of a type that can be categorized (string, choice, reference).
-
Index the Field:
- Pivot tables often work better with indexed fields. Ensure "Object ID" is indexed.
- Go to System Definition > Tables & Columns, find your field, and ensure the
Add to searchcheckbox is checked. Alternatively, you can configure an index from the Indexes related list on the table form.
-
Update the Dictionary Entry:
- Ensure the dictionary entry for the "Object ID" field is correctly set up.
- Go to System Definition > Dictionary, find the dictionary entry for the "Object ID" field, and make sure it is set as a reportable field.
-
Set Appropriate Permissions:
- Ensure you have the correct permissions.
- Check the ACL settings (go to System Security > Access Control (ACL)) to make sure you have read access to both the resource table and the particular field.
-
Configure the Report Builder:
- When building your pivot report, ensure the data source includes the required field.
- Go to Reports > Create New and select the appropriate data source.
- Configure the pivot options to include the "Object ID" field in the Rows or Columns by dragging and dropping it, ensuring it’s available in the list.
Example:
-
Data Source Configuration:
- Go to Reports > Create New.
- Choose the data source related to your cloud resource table.
- Ensure the Object ID is visible within the list of fields.
-
Configure Rows and Columns:
- Drag the "Object ID" field into the Rows or Columns section.
- If the field is not available, check the filters to ensure it’s not excluded.
Troubleshooting Tips:
-
Clear Cache and Re-index:
- Sometimes, changes might not be immediately visible due to caching. Clear the cache or re-index the table.
- Quick Re-Index: Go to System Definition > Tables, select the table, and click on the gear icon then choose Rebuild Table Index.
-
Testing with Different Data Types:
- Test with similar fields of known working types (e.g., string or choice fields) to determine if the issue is specific to the field type.
-
Review Sample Data:
- Ensure there is valid data for the "Object ID" in the table, as pivot tables depend on actual data to populate these categories.
Conclusion:
If, after following these steps, the "Object ID" field is still not available, it might require looking deeper into the ServiceNow configuration or potentially reaching out to ServiceNow support for advanced troubleshooting. Specific configurations or customizations in your instance could also be influencing this behavior.
-
- User
I am trying to fetch the incident ticket by using the REST API. I am able to get the reference link in the JSON format but i am not getting the actual incident ticket link. Could any one please help me on this.
- Assistant
When you fetch records like Incident tickets using the ServiceNow REST API, the response typically includes a reference link rather than the actual data of any referenced fields. This is by design to keep the response payload smaller and more manageable. Here's how you can handle it and get the actual data you need.
Understanding the Response
When you fetch an incident using the ServiceNow REST API, your response may look something like this:
{ "result": [ { "sys_id": "c8c0c8e76f05934004bdd01ab22950dc", "number": "INC0010001", "caller_id": { "link": "https://<instance>.service-now.com/api/now/table/sys_user/6816f79cc0a8016401c5a33be04be441", "value": "6816f79cc0a8016401c5a33be04be441" }, "short_description": "Unable to connect to VPN", "state": "2", "sys_created_on": "2023-08-01 10:00:00", "sys_updated_on": "2023-08-01 10:05:00" } ] }In the response above, you see the
caller_idas a reference link and value. To get the actual details of the referenced user, you can follow the link provided.How to Fetch Actual Reference Data
Step 1: Fetch the Incident
Make a call to the ServiceNow API to get the incident ticket:
GET https://<instance>.service-now.com/api/now/table/incident?sysparm_query=number=INC0010001Step 2: Fetch Reference Data
Once you have the reference link, you need to make another API call to retrieve the actual details. For instance, if you need details of the
caller_id:GET https://<instance>.service-now.com/api/now/table/sys_user/6816f79cc0a8016401c5a33be04be441Combining Data: Glide Script Example
If you need to automate the process and fetch all details in one go, you can use server-side scripting (Glide script) to fetch incidents along with related fields.
Example Glide Script
(function() { var result = {}; var incidentGR = new GlideRecord('incident'); if (incidentGR.get('number', 'INC0010001')) { result.sys_id = incidentGR.getValue('sys_id'); result.number = incidentGR.getValue('number'); result.short_description = incidentGR.getValue('short_description'); result.state = incidentGR.getValue('state'); result.sys_created_on = incidentGR.getValue('sys_created_on'); result.sys_updated_on = incidentGR.getValue('sys_updated_on'); // Fetch caller details var callerGR = new GlideRecord('sys_user'); if (callerGR.get(incidentGR.getValue('caller_id'))) { result.caller_id = { sys_id: callerGR.getValue('sys_id'), name: callerGR.getValue('name'), email: callerGR.getValue('email') }; } } return result; })();Extended API Call using URL Parameters
You can extend your API call to include data from referenced fields directly by using the
sysparm_fieldsparameter or thesysparm_display_valueparameter to get display values instead of just Sys IDs.Example API Call:
GET https://<instance>.service-now.com/api/now/table/incident?sysparm_query=number=INC0010001&sysparm_display_value=trueWith
sysparm_display_value=true, this will give you the display values for reference fields instead of just the Sys ID.Utilizing
sysparm_exclude_reference_linkIf you need to exclude reference links and just want the display values in the response:
GET https://<instance>.service-now.com/api/now/table/incident?sysparm_query=number=INC0010001&sysparm_display_value=true&sysparm_exclude_reference_link=trueExample of Query Parameters
sysparm_query: To filter the data.sysparm_display_value=true: To get the display value of fields.sysparm_exclude_reference_link=true: To exclude reference link from the response.
Conclusion
By making additional REST API calls to the reference links or by using URL parameters such as
sysparm_display_valueandsysparm_exclude_reference_link, you can fetch complete and detailed information about incident tickets and their related records. This approach provides flexibility in handling related data within ServiceNow's REST API framework without requiring complex client-side processing. - User
we are using select box field in catalog form, in that select box we have to display different LOV's as per the company data. so for showing those i am using a catalog client script to add and remove option from the select box, but when the end user using different language on portal than on that time also LOV displays in english language, it does not translates.
below is my code to add and remove option from select box field
function onChange(control, oldValue, newValue, isLoading) { if (isLoading || newValue == '') { return; } g_form.removeOption('supplier_subtype', 'Foreigner'); g_form.removeOption('supplier_subtype', 'Individual'); g_form.removeOption('supplier_subtype', 'Small Business'); g_form.removeOption('supplier_subtype', 'Corporate'); g_form.removeOption('supplier_subtype', 'None of the Above'); if (newValue == '81ac26d8dbaefa005d625434ce9619c5' || newValue == '0f9c5b07dbd51b40bc31c170ba9619dc') { g_form.addOption('supplier_subtype', 'Individual', ('Individual')); g_form.addOption('supplier_subtype', 'Corporate', 'Corporate'); g_form.addOption('supplier_subtype', 'None of the Above', 'None of the above'); } else { g_form.addOption('supplier_subtype', 'Foreigner', 'Foreigner'); g_form.addOption('supplier_subtype', 'Individual', 'Individual'); g_form.addOption('supplier_subtype', 'Small Business', 'Small Business'); g_form.addOption('supplier_subtype', 'None of the Above', 'None of the above'); } }
- Assistant
When configuring options dynamically in a ServiceNow catalog client script and you have to support multiple languages, hardcoding the option values and labels in English won't allow them to be automatically translated according to the user's language settings. Instead, you need to leverage ServiceNow's localization features.
Here's how you can modify your script to support localization:
-
Use the
getMessagefunction: This function fetches the localized message string for a given key. The localization messages are defined in the Messages table (sys_ui_message). -
Define Translation Strings: Ensure the localized strings are defined in the Messages table for all the languages you support.
-
Refactor your Script: Update your script to use the
getMessagefunction to retrieve the translated string.
Step-by-Step Solution:
Step 1: Define Messages
In the ServiceNow application navigator, go to the System UI > Messages module and create entries for all your options in all the supported languages.
For example, add entries like:
- Key:
Foreigner, Message:Foreigner(English) - Key:
Foreigner, Message:Extranjero(Spanish) - Key:
Individual, Message:Individual(English) - Key:
Individual, Message:Individuo(Spanish) - etc.
Step 2: Update the Client Script
Use the
getMessagefunction in your client script to ensure the values are correctly localized.Updated Client Script:
function onChange(control, oldValue, newValue, isLoading) { if (isLoading || newValue == '') { return; } // Remove existing options var optionsToRemove = ['Foreigner', 'Individual', 'Small Business', 'Corporate', 'None of the Above']; for (var i = 0; i < optionsToRemove.length; i++) { g_form.removeOption('supplier_subtype', optionsToRemove[i]); } // Define your options dynamically var options = []; if (newValue == '81ac26d8dbaefa005d625434ce9619c5' || newValue == '0f9c5b07dbd51b40bc31c170ba9619dc') { options = [ { value: 'Individual', label: getMessage('Individual') }, { value: 'Corporate', label: getMessage('Corporate') }, { value: 'None of the Above', label: getMessage('None of the above') } ]; } else { options = [ { value: 'Foreigner', label: getMessage('Foreigner') }, { value: 'Individual', label: getMessage('Individual') }, { value: 'Small Business', label: getMessage('Small Business') }, { value: 'None of the Above', label: getMessage('None of the Above') } ]; } // Add the appropriate options for (var j = 0; j < options.length; j++) { g_form.addOption('supplier_subtype', options[j].value, options[j].label); } }Explanation:
- The
getMessagefunction is used to fetch the localized string for each option. - The options are defined and added dynamically based on the
newValue. - This approach ensures that the labels for the options are displayed in the user's selected language.
Conclusion:
By using this updated approach with the
getMessagefunction and ensuring your messages are correctly defined in thesys_ui_messagetable, you can support multi-language environments and have the options in your select box display the appropriate language according to the user's settings.This way, your end-users will see the options in their preferred language, enhancing their experience with the ServiceNow portal.
-