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;


This one is problematic but there's a workaround...

UserTerritory is not permitted for DML from Apex. This is true for several SObjects as documented in the Apex Developer's Doc

However, the UserTerritory object can be created using the API as per the Apex SObject Reference

So, your VF controller is going to have to do a callout to the REST API using the same session ID as the running user to do the insert. There's an example here (using DatedConversionRates but the example can be adapted for UserTerritory)

| improve this answer | |
  • That helped @Cropredy. How do I write test class for this. I am getting 'you have uncommitted work pending. please commit or rollback before calling out' error while running the test class. Is it not because DML is being performed as part of the Callout. – starhunter Jul 14 '16 at 8:10
  • @starhunter -- best to post this as a new question, be sure to include only the 'essence' of your code + testmethod. You certainly will need to mock the callout in the testmethod – cropredy Jul 14 '16 at 13:18

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.