0

I am new to the salesforce I am facing following issue.

I want to show error message where I want to Display the userName and associated territory name. I am not able to get the both. Can you please help me on this?

{
    Map<Id,String> Uterr = new Map<Id,String>();
    List<Territory> terr = [SELECT Name, Id FROM Territory];
    for(Userterritory ut : [SELECT UserId, Territoryid FROM Userterritory WHERE UserId = UserId]) {
        for(Territory t: terr) {
            if(t.Id==ut.TerritoryId) { Uterr.put(ut.UserId,t.Name); 
        }
     }
}
  • Please post the code of what you did so far. – Martin Lezer Feb 14 '18 at 9:19
  • Map<Id,String> Uterr = new Map<Id,String>(); List<Territory> terr = [SELECT Name, Id FROM Territory]; for(Userterritory ut : [SELECT UserId, Territoryid FROM Userterritory WHERE UserId = UserId]) { for(Territory t: terr) { if(t.Id==ut.TerritoryId) { Uterr.put(ut.UserId,t.Name); } } } I am only able to get the user id not username . but I want to UserName and territory name to be displayed. May be I am doing something wrong. – Jay Feb 14 '18 at 9:22
0

You can query all of this with one query indeed. You should read this documentation. This is SOQL basic stuff.

Also, I assume that a user can have multiple territories assigned. So The Map value must be of type List<String>.

Here's the right code:

{
    Map<Id,List<String>> Uterr = new Map<Id,List<String>>();
    for(Userterritory ut : [SELECT UserId, Territory.Name FROM Userterritory WHERE UserId = :UserId]) {
          if(Uterr.containsKey(ut.UserId)){
              Uterr.get(ut.UserId).add(ut.Territory.Name);
          }else{
              Uterr.put(ut.UserId,new List<String>{ut.Territory.Name});
          }
     }
}
  • Thanks @Martin for the Response. But I am getting the below error. "Line: 2, Column: 28 SELECT UserId, Territory.Name FROM Userterritory ^ ERROR at Row:1:Column:16 Didn't understand relationship 'Territory' in field path. If you are attempting to use a custom relationship, be sure to append the '__r' after the custom relationship name. Please reference your WSDL or the describe call for the appropriate names. " Territory.Name field causing the error. – Jay Feb 14 '18 at 9:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.