I am working on a scenario where a user fills a form containing the field 'Area Code'. Based on the value of Area Code , the user has to be assigned to a territory(by matching the Area Code with a custom field on Territory object). So my initial understanding is to query on Territory object and get the territoryId of the Area Code. And then create (by inserting)a UserTerritory record whose TerritoryId is achieved above. But I am getting an error 'DML not allowed on User Territory' on doing an insert. I googled to find there is a create function for this. How would this work?
Below is the code snippet
public string AssignTerritory(String AreaCode){
List<UserTerritory> lstUserTerritory = new list<UserTerritory>();
List<Territory> lstTerritory = new List<Territory>();
lstTerritory = [Select id from Territory WHERE ISO_Country_Code =: AreaCode];
if(lstTerritory.size()>0 && lstTerritory!=null){
//List<UserTerritory> lstUserTerritory = [Select UserId, Territory.Name from UserTerritory where TerritoryId =: lstTerritory[0].id];
}
if(lstUserTerritory==null && lstUserTerritory.size()==0){
UserTerritory UTerritory = new UserTerritory();
UTerritory.UserId = UserInfo.getUserId();
UTerritory.TerritoryId = lstTerritory[0].id;
//UTerritory.IsActive = true;
//lstUserTerritory.add(UTerritory);
create(UTerritory);
}
}