Workspace button from Ui action

adilaleepan
Tera Contributor

adilaleepan_0-1761917383772.png

i want when some ones click the favorite button the value add in list field that name is also favorite 
|favorite button click = favorite field that type is list any one can guide me?

 

3 REPLIES 3

SVimes
Kilo Sage

With that script being a client script, move the actual scripting into the base script field above. The server functions and variables like gs and current aren't going to work. Leave the Workspace Client Script field empty or doing nothing. I'm using the Assign to me UI Action as an example because it has Workspace Form Button = true but it only has the normal script field doing anything.

Sable Vimes - CSA

Connectmustaq
Giga Guru

Hi @adilaleepan ,

 

Your script is almost correct for adding a user to a favorites field when the "favorite" button is clicked, but let's clarify its use for a ServiceNow "List" type field. Typically, a ServiceNow List field stores values as a comma-separated string; each click should add the new user ID to this list, unless already present.

 

Guidelines for List Field Implementation

  • Confirm Field Type: Ensure your field u_favorite is of type "List" (not Reference or String).

  • Script Logic: Your script checks if the user is in the favorites already; if not, it adds their user ID to the field.

The following script will work for standard "List" (comma-separated string) type fields:

 

(function() {
var currentUser = gs.getUserID();
var currentFavorites = current.getValue('u_favorite') || '';

// Convert to array for easy checking
var favoritesArray = currentFavorites ? currentFavorites.split(',') : [];

if (favoritesArray.indexOf(currentUser) > -1) {
gs.addInfoMessage('Already in favorites!');
} else {
favoritesArray.push(currentUser);
current.setValue('u_favorite', favoritesArray.join(','));
current.update();
gs.addInfoMessage('Added to favorites successfully!');
}

action.setRedirectURL(current);
})();

 

  • This approach handles the field as an array and avoids duplicates.

  • If your "favorite" field is configured as a real ServiceNow List field, this method works as ServiceNow treats "List" fields as comma-separated strings behind the scenes.

Steps to Use in ServiceNow

  • Add this script to your UI Action that triggers on button click.

  • Make sure the "favorite" field exists and is the correct type on your table.

  • Test by clicking the Favorite button. Your user ID should be appended to the list field on the record each time, unless already present.

If it is helpful, please hit the thumbs button please mark the answer as correct based on the impact!!

 

 

Kind Regards,

Shaik Mohammed Mustaq

RaghavSh
Mega Patron

@adilaleepan gs.getUserID()/current is server side code cannot be used in client side script. Please use the client side coding standard.


Please mark the answer correct/helpful accordingly.


Raghav
MVP 2023
LinkedIn