0

I have a very simple trigger which is working fine in the sandbox but it doesn't work in the production. If someone change the owner of the opportunity or add a new opportunity the customfield team__c should be filled with the owner team value. But if I change the owner the field keep blank. If I change the team field at the opportunity manuelly and then I change the owner then becomes the field also blank.

trigger setTeamOpportunity on Opportunity (before update) {

 for(Opportunity o : trigger.new) { 
     Opportunity oldOpportunity = trigger.OldMap.get(o.ID);
         if(o.ownerid != oldOpportunity.ownerid) {
                    o.Team__c = o.Owner.Team__c;
         }
     }
}

2 Answers 2

1

This trigger should not work in any environment.

o.Team__c = o.Owner.Team__c;

The Owner.Team__c field, like all fields across relationships from the trigger object, is available to you only if you perform a SOQL query. You're getting blanks because it's treated as being null.

2
  • ok, how can I fix it? But its strange, in sandbox it works.
    – peXeq
    May 10, 2019 at 11:37
  • There are a number of good examples if you search SFSE for "relationship field trigger". Try this one.
    – David Reed
    May 10, 2019 at 11:38
0

Now it works with the following code

trigger setTeamOpportunity on Opportunity (before insert, before update) {

 if(Trigger.isInsert) {
   for(Opportunity o : trigger.new) { 
         List <User> UserList = [SELECT Team__c FROM User WHERE Id = :o.OwnerId];
         FOR (User USL : UserList) {
            o.Team__c = USL.Team__c;
        }
    } 
 } ELSE { 

  for(Opportunity o : trigger.new) { 
     Opportunity oldOpportunity = trigger.OldMap.get(o.ID);
         if(o.OwnerId != oldOpportunity.Ownerid) {

         List <User> UserList = [SELECT Team__c FROM User WHERE Id = :o.OwnerId];
         FOR (User USL : UserList) {
            o.Team__c = USL.Team__c;
        }
    } 
}
}
}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .