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

Bhavya11
Kilo Patron
Kilo Patron

hi @markdart ,

 

As per best practice it should be through ACls, but if want to achieve it you can use Onload Client Script and use the below sample code : 

 

if(g_user.hasRoleExactly('timecard_admin '))
{
g_form.setReadOnly('fieldName1', false);
}

 

 

If this information proves useful, kindly mark it as helpful or accepted solution.

Thanks,

BK

anshul_goyal
Kilo Sage

Hello @markdart,

Please use client script instead of UI Policy, if you're doing some scripting:

function onLoad() {
    // Check if the current user does NOT have the 'timecard_admin' role
    if (!g_user.hasRoleExactly('timecard_admin')) {
        g_form.setReadOnly('your_field_name', true);
    } else {
        g_form.setReadOnly('your_field_name', false);
    }
}


Please mark my solution as helpful and accepted for future reference.

Thanks

Shubham_Jain
Mega Sage
Mega Sage

@markdart 

 

  1. Is the field already read-only via Dictionary or ACL?
    UI Policies can't override read-only settings from Dictionary or ACLs.

 

✔️ If this solves your issue, please mark it as Correct.


✔️ If you found it helpful, please mark it as Helpful.



Shubham Jain