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

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
Giga 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
5x ServiceNow MVP

View solution in original post

Voona Rohila
Giga 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
5x ServiceNow MVP

View solution in original post

3 REPLIES 3

Voona Rohila
Giga 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
5x ServiceNow MVP

Voona Rohila
Giga 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
5x ServiceNow MVP

Hey, @Voona Rohila  thanks it worked