You need to sign in to do that
Don't have an account?
Trigger to assign value of lookup User field
Hi all,
I have a custom object Territory__c in which there is lookup(User) Regional_Director field. I am trying to assign the Regional Director to appropriate user.
Following is the code in a trigger I have and want to update the regional director lookup field after insert. However it gives the following error: "Regional Director: id value of incorrect type:". It looks like terr.regional_director__c returns a SObject so the assignment may not work, how can I get it working? Thanks much for your help.
trigger addSalesDirReps on Territory__c (before insert) {
Territory__c [] territoryList = trigger.new;
List <Territory__c> updatedListToInsert= new List <Territory__c>();
for(Territory__c terr: territoryList){
List<User> lookupRMUser = [select Id from User where Name=:terr.Regional_Director_Name__c];
terr.regional_director__c = lookupRM[0].Id;
updatedListToInsert.add(terr);
}
insert updatedListToInsert;
}
Ok, first issue is you are using a SOQL statment inside a for-loop. This will cause you problems.
First you should create a map of ids for users and their managers. Then use that map to assign the value based on the division. This will help you in your trigger to handle bulk records.
Thanks much for you suggestion. Sorry, not sure if I understand, I am beginner in APEX programming
Please can you give me an example. Thanks much.
Try this trigger
Also optimize your trigger check this :
http://forceschool.blogspot.com/2011/05/writing-apex-trigger-save-limits-in.html
Since you're writing a before trigger on Territory, you don't need an explicit Insert.
trigger addSalesDirReps on Territory__c (before insert) {
Map<String, Territory__c > userTerritoryMap = new Map<String, Territory__c>{};
for(Territory__c terr: Trigger.New)
userNames.put(terr.Regional_Director_Name__c, terr); //assuming Regional Director names will be unique
for(User u : [select Id, Name from User where Name IN :userTerritoryMap.keySet()]) {
Territory__c territ = userTerritoryMap.get(u.Name) ; //get corresponding territory for user from map
territ.regional_director__c = u.Id; //set regional director id from map
}
if(userTerritoryMap != null && !userTerritoryMap.isEmpty())
Database.update(userTerritoryMap);
}
Thanks all, I will try the solutions and get back!