Add/ Remove a specific role from user profile when user is Added/removed from a particular field.

Puneet4418
Tera Contributor

Hello Developers,

 

Can someone help me with below requirement.

There is a field "Owner" in a custom application form. whenever any user added to that field, a specific role should be automatically added to the user's profile and vice versa when removed from the field. How can we achieve this?

1 ACCEPTED SOLUTION

@Puneet4418 In your business rule, can you update as follows.

 

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.info(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
               gs.info('Previous owner '+previous.u_owner);
                if(removeRole.next()){
                 gs.info('Deleting the record '+ removeRole.getValue('sys_id'));
                    removeRole.deleteRecord();
                }
            }

        }
    }
}

 

Can you check if both the info logs are printed and what values do they print.

 

View solution in original post

10 REPLIES 10

@Puneet4418 Can you share the screenshots of your business rule, please include all sections 'When to run, action and advanced in your screenshots

@Sandeep RajputI found the issue. Now its working fine.

@Sandeep Rajput I have been looking at this as I have the same requirement. The problem i'm getting is that when I add a user to my custom field, the role is added to the profile. When you then add an additional user after the first user it then gives a unique key violation and removes the role from the user still in the custom field. Any idea why this is? 

@Luke James Could you please post a separate question with screenshot of your business rule and form where you are facing this issue.

Jaspal Singh
Mega Patron
Mega Patron

Hi Pankaj,

Can you please share the need for such use case.