+ Start a Discussion

UserRole Heirarchy

I need to query all opportunities for a user and their subordinates in the UserRole heirarchy.    I currently create a set of UserRole Ids from all the UserRole records to do the query.  I wasn't sure if their is another way to accomplish this. Any recommendations?



Richie DRichie D

Hi Brian,


I'd have thought that if your class has 'with sharing' in the class then you would only get back opportunities the user is allowed to see according to the sharing rules if the sharing is setup correctly (ie. role hierarchy applied) .


If the sharing model doens't work for you then your function of getting the role hierarchy and creating your own select statement is the easiest way to go. Problems may occurr furter down the line if groups/queue functionality is implemented....







Richie D. thanks for you response.  I thought so too, so I created a test class using 3 different users in the heirarchy.  The test class returns 8710 records for all 3 users.  I created a report with identical criteria, it returned 8710, 5043, and 197 records when using the heirarchy.  


public with sharing class TESTHierarchy {
 public TESTHierarchy()
  List<Opportunity> oList = new List<Opportunity>();
  System.debug('Current User: ' + UserInfo.getUserName()); 
  System.debug('Current Profile: ' + UserInfo.getProfileId());		
  for (Opportunity o: [Select id from Opportunity where Owner.IsActive = true 
    and isDeleted=false and calendar_year(closeDate)>2010])

 public static testmethod void TestH1()
  User tUser1 = [Select id from User where id = '00530000000cDFi' limit 1];
  system.runAs(tUser1) {TESTHierarchy t1 = new TESTHierarchy();} 
 public static testmethod void TestH2()
  User tUser2 = [Select id from User where id = '00530000000dV6y' limit 1];
  system.runAs(tUser2) {TESTHierarchy t1 = new TESTHierarchy();} 
 public static testmethod void TestH3()
  User tUser3 = [Select id from User where id = '00530000000cDE0' limit 1];
  system.runAs(tUser3){TESTHierarchy t1 = new TESTHierarchy();}