The Zurich release has arrived! Interested in new features and functionalities? Click here for more

Make Approval state field read only unless I am the approver or an admin

Baggies
Kilo Guru

I am trying to make the state field on an approval form read_only, except for admin role, and also if the current user is the approver. I have set up a UI Policy to do this,but it doesn't appear to like the current user. This is the script I have in the Execute if true script:

function onCondition() {

      if ((g_user.userID == g_form.getValue( 'approver' )) || (g_user.hasRole("admin"))) {

              g_form.setReadOnly( "state", false );

                      } else {

              g_form.setReadOnly( "state", true );

            }

}

 

approvalUIPolicy.JPG

1 ACCEPTED SOLUTION

poyntzj
Kilo Sage

are using Calgary too and we use an ACL



type: record


operation: write


active: yes


admin overwrite: yes


name: sysapproval_approver         state


Add a condition if you want   (we have state is not "Not valid for this change"


script: answer = gs.hasRole('approval_admin') || isApprovalMine(current);


View solution in original post

9 REPLIES 9

justin_drysdale
Mega Guru

I think g_user is for the currently logged in user.   I am not sure if you can overwrite userID like that.   I am testing for a way to make g_user work with a non session user but am not having any luck yet....



However, this should work:



function onCondition() {


var approver = g_form.getValue('approver');


      if( checkRole(approver, "admin") ) {


          g_form.setReadOnly("state",false);


      }else{


          g_form.setReadOnly("state",true);


      }



function checkRole(user, role) {


  var role_check = new GlideRecord('sys_user_has_role');


          role_check.addQuery('user', user);


          role_check.addQuery('role', role);


          role_check.query();


          if( role_check.hasNext() ) {


              //user has role


              return true;


          }


          return false;


}


}


Hi Justin, excellent response, but this solution makes the 'state' field is now read only for all users. What I think I should have said was, if the 'logged in ' user is the approver, or has the admin role, then the field should NOT be read only. Many thanks, Mark S.


niedziel1
ServiceNow Employee
ServiceNow Employee

That GlideRecord query is expensive from a performance perspective.   You might consider my solution which won't have that same performance impact.


niedziel1
ServiceNow Employee
ServiceNow Employee

In the Condition Builder on the UI Policy form you could set the condition to be:



Approver         is (dynamic)         Me



This would test to see if the currently logged in user is the same as the value in the Approver field.   You'd still have to test for the admin role in your script.   You would need both a true and false script if you do it this way.




SetStateProperty.png