We've updated the ServiceNow Community Code of Conduct, adding guidelines around AI usage, professionalism, and content violations. Read more

auto populate loggedin user

Dhanaja Rode
Tera Contributor

When the checkbox of this field " This request is for myself " is true then auto populate as logged in user otherwise not

 

1 This request is for myself :  [ ✔️]

2 Requested for : should autopopulate logged in user

1 ACCEPTED SOLUTION

Saurabh Gupta
Kilo Patron

Hi @Dhanaja Rode 

 

Simply you can write a onChange client script and populate the logged in user using GlideUser API and g_form.setValue('req for var backend name',g_user.userID)

 

var userID = g_user.userID;

   alert('Current user ID = ' + userID);


Thanks and Regards,

Saurabh Gupta

View solution in original post

2 REPLIES 2

Saurabh Gupta
Kilo Patron

Hi @Dhanaja Rode 

 

Simply you can write a onChange client script and populate the logged in user using GlideUser API and g_form.setValue('req for var backend name',g_user.userID)

 

var userID = g_user.userID;

   alert('Current user ID = ' + userID);


Thanks and Regards,

Saurabh Gupta

AniketC85155510
Kilo Patron

Hello @Dhanaja Rode ,

Please give a try to the code below and let me know how it works for you.

function onChange(control, oldValue, newValue, isLoading, isTemplate) {
  if (isLoading || newValue === '')
    return;

  // Get the checkbox value
  var isForMyself = g_form.getValue('this_request_for_myself');

  // Get the Requested for field element
  var requestedForField = g_form.getControl('requested_for');

  // If the checkbox is checked, auto-populate with the logged-in user
  if (isForMyself) {
    var loggedInUser = g_user.userID;
    g_form.setValue('requested_for', loggedInUser);
    // Optionally, you can disable the Requested for field if it's auto-populated
    requestedForField.disabled = true;
  } else {
    // If the checkbox is unchecked, clear the Requested for field
    g_form.setValue('requested_for', '');
    // Optionally, you can enable the Requested for field if it was disabled
    requestedForField.disabled = false;
  }
}


This script assumes that the checkbox field has the variable name 'this_request_for_myself' and the Requested for field has the variable name 'requested_for'. Adjust the variable names accordingly based on your actual field names.

Let me know your views on this and Mark Correct if this solves your query and also mark 👍Helpful if you find my response worthy based on the impact.

 

Thanks,

Aniket