Sandeep Rajput
Tera Patron

@Puneet4418 Create an insert/update business rule on your custom table with condition owner changes. Inside the business rule script, add the following code.

 

if(current.u_owner!=previous.u_owner){
    var userRole = new GlideAggregate('sys_user_has_role');
    userRole.addQuery('user',current.u_owner);//replace with your 
    userRole.addQuery('role','b2d8f7130a0a0baa5bf52498ecaadeb4');//Add your role sys_id here
    userRole.addAggregate('COUNT');
    userRole.query();
    if(userRole.next()){
    var roleCount=0;
    roleCount= userRole.getAggregate('COUNT');
    gs.print(roleCount);
        if(roleCount==0){//Only add role if the user doesn't have it
            var glideRole = new GlideRecord('sys_user_has_role');
            glideRole.initialize();
            glideRole.user=current.u_owner;
            glideRole.role='b2d8f7130a0a0baa5bf52498ecaadeb4'; //replace with your role sys_id
            glideRole.state='active';
            glideRole.insert();

            if(previous.u_owner!=''){//Code to remove the role from previous owner.
                var removeRole = new GlideRecord('sys_user_has_role');
                removeRole.addQuery('user',previous.u_owner);
                removeRole.addQuery('role','b2d8f7130a0a0baa5bf52498ecaadeb4');//Replace with you role sys_id
                if(removeRole.next()){
                    removeRole.deleteRecord();
                }
            }

        }
    }
}

Hope this helps.