Read only on condition

markdart
Kilo Guru

I have a Field on Time Card I want to be Read only except when the user has timecard_admin role.

here is what I tried with no success. screenshots attached

1. UI Policy Script script execute if True 

function onCondition() {
  return !g_user.hasRole("timecard_admin");
}
2.UI Policy Action - User Read only True
 
The UI policy seems to be always running True when I tested with the diagnostics tool.
1 ACCEPTED SOLUTION

Ankur Bawiskar
Tera Patron
Tera Patron

@markdart 

please use onLoad client script and not UI policy

function onLoad() {
    // Check if the current user does NOT have the 'timecard_admin' role
    if (!g_user.hasRoleExactly('timecard_admin')) {
        // Make the field read-only for everyone except timecard_admin
        g_form.setReadOnly('your_field_name', true);
    } else {
        // Optional: Make sure the field is editable for timecard_admin
        g_form.setReadOnly('your_field_name', false);
    }
}

If my response helped please mark it correct and close the thread so that it benefits future readers.

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader

View solution in original post

7 REPLIES 7

Ankur Bawiskar
Tera Patron
Tera Patron

@markdart 

please use onLoad client script and not UI policy

function onLoad() {
    // Check if the current user does NOT have the 'timecard_admin' role
    if (!g_user.hasRoleExactly('timecard_admin')) {
        // Make the field read-only for everyone except timecard_admin
        g_form.setReadOnly('your_field_name', true);
    } else {
        // Optional: Make sure the field is editable for timecard_admin
        g_form.setReadOnly('your_field_name', false);
    }
}

If my response helped please mark it correct and close the thread so that it benefits future readers.

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader

Thanks heaps worked straight away, I spent two hours arguing with chatpgt yesterday🤣

@markdart 

Can't rely much on ChatGPT !

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader

Shraddha Kadam
Mega Sage

Hello @markdart ,

 

Create onload client script and use below code -

function onLoad() {
    if (g_user.hasRole('timecard_admin') == true) {
        g_form.setReadOnly('user', false);
        g_form.setMandatory('user', true);
    } else {
        g_form.setMandatory('user', false);
        g_form.setReadOnly('user', true);
    }

}
If my response was helpful, please mark it as correct and helpful.
Thank you.