Join the #BuildWithBuildAgent Challenge! Get recognized, earn exclusive swag, and inspire the ServiceNow Community with what you can build using Build Agent.  Join the Challenge.

How to delete the role based on the condition

Atik
Tera Contributor

Hello Experts,

I have a requirement where there is a field Position on the user table and its choice field and choices are 'Non-Agent' and 'Agent' if 'Non-Agent' then I have to remove the role.

I am trying by background script but not getting the expected result

Please help me with this.

 

var user = new GlideRecord('sys_user');

user.addQuery('u_position','non_agent');

user.query();

while (user.next()) {

    var hasRole = new GlideRecord('sys_user_has_role');

    hasRole.addQuery('user', user.sys_id);

    hasRole.addQuery('user.role', 'itil');

    hasRole.query();

    if (hasRole.next()) {

    hasRole.deleteRecord;

        

    }

}

Thanks in advance, atik.

2 ACCEPTED SOLUTIONS

Voona Rohila
Mega Patron
Mega Patron

Hi @Atik 

Logic is correct, The syntax for delete record method is - hasRole.deleteRecord();

Mark it helpful if this helps you to understand. Accept solution if this give you the answer you're looking for
Kind Regards,
Rohila V
2022-25 ServiceNow Community MVP

View solution in original post

Voona Rohila
Mega Patron
Mega Patron

You can also try this way without querying the user table.

     var hasRole = new GlideRecord('sys_user_has_role');
    hasRole.addQuery('user.u_position', 'non_agent');
    hasRole.addQuery('user.role', 'itil');
    hasRole.query();
    if (hasRole.next()) {
    hasRole.deleteRecord();
    }

 


Mark it helpful if this helps you to understand. Accept solution if this give you the answer you're looking for
Kind Regards,
Rohila V
2022-25 ServiceNow Community MVP

View solution in original post

3 REPLIES 3

Voona Rohila
Mega Patron
Mega Patron

Hi @Atik 

Logic is correct, The syntax for delete record method is - hasRole.deleteRecord();

Mark it helpful if this helps you to understand. Accept solution if this give you the answer you're looking for
Kind Regards,
Rohila V
2022-25 ServiceNow Community MVP

Voona Rohila
Mega Patron
Mega Patron

You can also try this way without querying the user table.

     var hasRole = new GlideRecord('sys_user_has_role');
    hasRole.addQuery('user.u_position', 'non_agent');
    hasRole.addQuery('user.role', 'itil');
    hasRole.query();
    if (hasRole.next()) {
    hasRole.deleteRecord();
    }

 


Mark it helpful if this helps you to understand. Accept solution if this give you the answer you're looking for
Kind Regards,
Rohila V
2022-25 ServiceNow Community MVP

Hey, @Voona Rohila  thanks it worked