in servicenow, i want to change the color of requested_for to red and show the vip badge in front of the field as same as incident form, if the requested_for user is VIP
Assistant
User
not working, in servicenow ootb this script is used for incident
function onChange(control, oldValue, newValue, isLoading) {
var callerLabel = ('sys_display.incident.caller_id');
if (!callerLabel || !callerField)
return;
Assistant
User
script is not working for sc_req_item form, give me the different method, to call business rule , sys_ui_style in client script
Assistant
User
nott working
Assistant
To achieve the customizations you want in ServiceNow, such as changing the color of the "requested_for" field to red and displaying a VIP badge next to it on a form (for example, on a Service Catalog Request form), you will need to use a combination of client scripts and UI policies or you could customize the form layout directly if the requirements are simple. Below is a general outline on how to implement this:
Step 1: Customize the Form Layout
Navigate to the Form: Go to the specific form where you want to add these customizations. For example, if you’re working with a catalog item request, navigate to that particular catalog item.
Configure the Form Layout: Right-click on the form header and select "Configure > Form Layout" to add or rearrange fields.
Step 2: Add a VIP Indicator
To add a VIP badge:
Create a new field or modify an existing one to show the VIP badge. This could be an image field or a string field that is conditionally displayed.
Modify the Dictionary Entry: Go to the User [sys_user] table and modify the dictionary of the field you want to use to show the VIP badge. You might want to add an attribute such as "image_path" if you plan to use an image to indicate a VIP user.
Step 3: Apply UI Policies or Client Scripts
Since this customization involves showing the VIP badge based on the user status and changing the color of the field, you will likely need to use both UI Policies for simple show/hide logic and Client Scripts for more complex behaviors.
UI Policy
Create a New UI Policy: Navigate to "System Policy > UI Policies".
Set Condition and Script: Make the policy apply only if the user in the "requested_for" field is marked as a VIP in their user record. You may need to add a custom field in the user table to indicate VIP status, such as a boolean field vip.
Client Script
Create a Client Script: Navigate to "System Definition > Client Scripts".
Add a Script Like Below (assuming "requested_for" is the field name and it's a reference field to the User table):
javascript
(function onLoad() {
var vipField = g_form.getReference('requested_for', function(ref) {
if (ref.vip) { // Assuming 'vip' is the field denoting VIP users
// Change color of the field
var field = g_form.getGlideUIElement('requested_for');
if (field) {
field.getElement().style.color = 'red';
}
// Add VIP badge
var badgeElement = "<img src='/path_to_vip_icon.png' style='height:16px;width:16px;'>";
var label = document.querySelector("label[for='" + field.getID() + "']");
if (label) {
label.innerHTML = badgeElement + label.innerHTML;
}
}
})
})();
Step 4: Security and Performance Considerations
Security: Make sure that any scripts do not expose sensitive information and are only pulling necessary data.
Performance: Keep in mind that adding client-side scripts can affect the performance of the form load time, especially if referring to many external resources or performing complex manipulations.
Testing
Thoroughly test the new configuration in a sub-production instance before rolling out changes to the production environment.
Ensure that the implementation works across all browsers that your organization supports.
By following these steps, you should be able to achieve the required customization in ServiceNow to highlight VIP users in specific forms effectively.
function vipCallerCallback(caller) {
var callerLabel = (′label.incident.callerid′).down(′label′);varcallerField=('sys_display.incident.caller_id');
if (!callerLabel || !callerField)
return;
code
//check for VIP status
if (caller.vip == 'true') {
var bgPosition = "95% 55%";
if (document.documentElement.getAttribute('data-doctype') == 'true')
bgPosition = "5% 45%";
callerLabel.setStyle({backgroundImage: "url(images/icons/vip.gif)", backgroundRepeat: "no-repeat", backgroundPosition: bgPosition, paddingLeft: '30px' });
callerField.setStyle({color: "red"});
} else {
callerLabel.setStyle({backgroundImage: ""});
callerField.setStyle({color: ""});
}
}
To apply similar VIP visual indicators to a different form in ServiceNow such as a Service Catalog item or the Requested Item (sc_req_item) form in ITSM, you'll need to adapt the script you've provided, which is designed for an Incident form, to work with different field names and possibly different conditions depending on the table structure.
Adjusting the Script for Service Catalog or Other Forms
Here’s how you can adapt your previous client script for the Requested Item or a custom catalog form, focusing on a different field such as requested_for. Note that for simplicity, I'm assuming the requested_for field is similar to the caller_id field on the Incident form, being a reference to the User [sys_user] table with a VIP indicator (a boolean).
1. Create a New Client Script
Navigate to "System Definition > Client Scripts" and create a new script. Select the appropriate table (like Catalog Task [sc_task] or a custom table) and set the type to onChange.
2. Adapt the Client Script
You need to update the script to target the correct field (e.g., requested_for) and ensure the selectors match those in your form.
javascript
function onChange(control, oldValue, newValue, isLoading) {
if (isLoading || newValue === '') {
clearVIPStyles();
return;
}
g_form.getReference('requested_for', vipRequestedForCallback);
}
function clearVIPStyles() {
var requestLabel = $('label.sc_req_item.requested_for').down('label');
var requestField = $('sys_display.sc_req_bulk.requested_for');
if (requestLabel && requestField) {
requestLabel.setStyle({backgroundImage: ""});
requestField.setStyle({color: ""});
}
}
function vipRequestedBackCallback(user) {
var requestLabel = $('label.sc_req_item.requested_for').down('label');
var requestField = $('sys_display.sc_req_bulk.requested_for');
if (!requestLabel || !requestField)
return;
if (user.vip == 'true') {
var bgPosition = "5% 45%";
if (document.documentElement.getAttribute('data-doctype') == 'true')
bgPosition = "95% 55%";
requestLabel.setStyle({
backgroundImage: "url(images/icons/vip.gif)",
backgroundRepeat: "no-repeat",
backgroundPosition: bgPosition,
paddingLeft: '30px'
});
requestField.setStyle({color: "red"});
} else {
clearVIPStyles();
}
}
Explanation:
Selector Adjustments: Make sure your selectors ($('label.sc_req_item.requested_for')) match the actual HTML structure of your form. They might differ based on your instance's configuration and version.
Reference Fields: The script uses g_form.getReference('requested_for', callback) to get the user record linked in the requested_for field and checks the VIP status.
CSS Styles: As in the original script, here the styles and badge placement are adjusted based on whether ServiceNow is in doctype mode. Adjust backgroundPosition, paddingLeft, and icon URL as needed.
3. Test the Script
Apply the script to a development or test instance.
Test the functionality by selecting both VIP and non-VIP users in the requested basck field to ensure that the VIP badge appears and disappears accordingly, and that the field color changes to red for VIPs.
Troubleshooting Tips:
Selectors: The most common issue while adapting these scripts is incorrect selectors. Inspect the HTML of your form to ensure your script targets the correct elements.
Permissions: Ensure that the client script has access to all fields it interacts with and that the VIP field is correctly set up in the User table.
By carefully adjusting the script and thoroughly testing it in your environment, you can achieve a consistent VIP indication across different forms in ServiceNow.
If the direct approach with client scripts has proven challenging due to CSS styling issues or DOM element complexities on the sc_req_item form, an alternative method involves using a Business Rule to set UI styles programmatically. This involves utilizing the sys_ui_style table to dynamically apply styles based on the conditions you define server-side in a Business Rule.
Step-by-Step Process to implement VIP styling via Business Rule and sys_ui_style:
Step 1: Identify or Create a VIP Indicator Field
First, ensure there is a field in the User [sys_user] table that indicates VIP status. This should ideally be a boolean field (e.g., vip). You can check this by navigating to User table (sys_user) and confirming the presence of such a field.
Step 2: Create a Business Rule
Create a Business Rule that triggers on inserts or updates on relevant tables (like sc_req_item). This Business Rule should apply styles by creating or modifying records in the sys_ui_style table based on VIP status.
Navigate: Go to System Definition > Business Rules.
Create New Rule: Define a new rule with the following characteristics:
Name: Apply VIP Style
Table: sc_req_item (or another relevant table)
Advanced: Yes
When to run: Before Insert and Before Update
Script:
javascript
(function executeRule(current, previous /*null when async*/) {
// Function to remove any existing style for a field
function clearStyles(fieldName) {
var gr = new GlideRecord('sys_ui_style');
gr.addQuery('name', fieldName);
gr.addQuery('table', 'sc_req_item');
gr.query();
while (gr.next()) {
gr.deleteRecord();
}
}
// Function to apply or clear VIP style
function updateVIPStyle(userSysId, fieldName) {
clearStyles(fieldName); // Clear existing styles first
var userGR = new GlideRecord('sys_user');
if (userGR.get(userSysId)) {
if (userGR.vip) {
var styleRec = new GlideRecord('sys_ui_style');
styleRec.initialize();
styleRec.name = fieldName;
styleRec.table = 'sc_req_item';
styleRec.style = 'color:red'; // Style for VIP
styleRec.insert();
}
}
}
// Calling the function with current Requested For user
updateVIPStyle(current.requested_for, 'requested_for');
})(current, previous);
Step 3: Update and Test
After setting up the Business Rule:
Update an existing record or create a new one in sc_req_item where the Requested For field links to a VIP user.
Check to ensure the requested_for field appears with a red color due to the dynamically applied style.
Notes:
Performance Concerns: Frequently modifying sys_ui_style entries can have performance implications. Ensure you really need dynamic, per-user/per-field styling before adopting this approach.
Visibility and Maintenance: Styles applied via sys_ui_style can sometimes be difficult to debug and maintain since they aren't visible directly on the field or form.
Alternatives:
If the direct method through client scripts is preferable (due to simplicity or performance reasons), consider revisiting the initial approach and ensuring that elements are targeted correctly and that sufficient rights and conditions exist to apply styles through Client Scripts. Correct your DOM selectors and test in different browsers or configurations. Also, ensure that modifications are compatible with your specific ServiceNow version's layout and customizations.
This Business Rule method utilizing sys_ui_style offers a robust server-side approach, enabling consistent styling across users and sessions, enforced centrally within ServiceNow's data layer.
I apologize for the inconvenience you're experiencing. Let's try a different method using a Client Script and Data Lookups for a maintainable and effective solution to display VIP visuals on the sc_req_item form.
Approach:
Instead of manipulating styles through business rules and sys_ui_style, let's use a Data Lookup rule to automatically update a descriptor field on the sc_req_item record when a VIP user's data is selected in the requested_for field. Then, use a Client Script to modify the form based on the descriptor set by the Data Lookup.
Step 1: Setup a Descriptor Field
First, add a new field to your sc_req_item table to store VIP status information:
Go to System Definition > Tables & Columns.
Navigate to the sc_req_item table.
Add a new field (e.g., VIP_status_descriptor) with type "String".
Step 2: Data Lookup Definitions
Create a Data Lookup definition to update the descriptor when VIP status changes based on requested_for:
Navigate to System Policy > Data Lookup Definitions.
Create a new Definition:
Source table: User [sys_user]
Target table: Requested Item [sc_req_item]
Set conditions to check if the vip field on the User table is true.
In the Field Maps, map vip (or equivalent) from the User table to your new VIP_status_descriptor field on the sc_req_item, perhaps setting it to "VIP" if true.
Step 3: Client Script for UI Modification
With the descriptor in place, you now simply need a Client Script to check this field and modify the UI accordingly.
Navigate to System Definition > Client Scripts.
Create a new Client Script with these settings:
Type: onCellEdit or onLoad (depending on your preference for when the adjustment should occur)
Table: sc_req_item
javascript
function onLoad() {
// Use setTimeout to delay execution until after the form has fully loaded
setTimeout(function() {
var vipStatus = g_form.getValue('VIP_status_descriptor');
if (vipStatus === 'VIP') {
// Apply CSS style changes directly
var el = g_form.getControl('requested_for');
if(el) {
el.style.color = 'red'; // Change color
// Add an icon (ensure the path to the icon is correct)
var parentElement = el.parentNode;
if (parent +_element.getElementsByClassName('vip_icon').length === 0) { // Avoid multiple icons
var vipIcon = document.createElement('img');
vipIcon.src = "images/icons/vip.gif";
vipIcon.className = "vip_icon";
vipIcon.style.height = "16px";
vipIcon.style.width = "16px";
parentElement.appendChild(vipIcon);
}
}
} else {
// Optional: Clear styles if not VIP
var el = g_form.getControl('requested_for');
if(el) {
el.style.color = ''; // Reset color
var icons = el.parentNode.getElementsByClassName('vip_icon');
while (icons[0]) {
icons[0].parentNode.removeChild(icons[0]);
}
}
}
}, 500);
}
Step 4: Evaluate & Adjust
Deploy the changes on your development or testing environment.
Create or update sc_req_item records to ensure the Data Lookup and Client Scripts are functioning correctly.
Explanation:
This approach utilizes Data Lookup to manage data-driven changes (like identifying VIP status), ensuring that the form reacts automatically. The Client Script then visually represents these changes by altering UI aspects based on the descriptor's value.
This method offers the benefits of visibility, simplicity in debugging, and maintainability by keeping the data logic (VIP identification) and presentation (JavaScript/CSS modifications) somewhat separate. Also, it avoids direct manipulation of the sys_ui_style table, which can have broader unintended effects if not carefully managed.