0

I have one trigger on Opportunity which will copy the value of some Account field into opportunity field. All I'm doing in before trigger because I also have validation rule on opportunity which will fire on opportunity.

But in before trigger my values are not getting updated. here is my code:

for(Opportunity op : Trigger.New){

    op.Checkbox1 = op.Account.Wal_Checkbox1;
    op.Checkbox2 = op.Account.Wal_Checkbox2;
    op.Checkbox3 = op.Account.Wal_Checkbox3;
    op.Checkbox4 = op.Account.Wal_Checkbox4;

}
3
  • 2
    Just use formula fields. No need for a trigger
    – Eric
    Commented Dec 22, 2016 at 21:08
  • due to some business login I can't move them to formula Commented Dec 22, 2016 at 21:10
  • What business logic? The value will be the same regardless if they are populated via trigger or as a formula field. Maybe the business logic is flawed or misunderstood
    – Eric
    Commented Dec 22, 2016 at 21:45

2 Answers 2

2

In Trigger.New (Context variables), you can not reference relationship object fields. Ex: Opportunity.Account.Name. In Trigger Name will not be available.

  • You will need to perform separate query to get those fields from Account.

  • Use some collection like Map<Id,Account> to have Opportunity's Account Id and its Account in a map.

  • When you iterate opportunity (Trigger.New), pass the Opportunity's Account Id to get Account fields

  • Assign those fields in relevant Opportunity fields.

4
  • Earlier I was doing same thing but it was not working List<Id> accListId = new List<Id> for(Opportunity opp : Trigger.New){ accListId.add(opp.AccountId); } Commented Dec 22, 2016 at 21:19
  • for(Opportunity op : [Select Id,Account.Checkbox4,Account.Checkbox3,Account.Checkbox2, Account.Checkbox1,Checkbox4,Checkbox1, Checkbox3,Checkbox2 from Opportunity where AccountId IN : accListId]){ system.debug('..33.. '+op); if(op.Account.Checkbox4 != null){ op.Checkbox4 = op.Account.Checkbox4; } } Commented Dec 22, 2016 at 21:19
  • @salesforceDeveloper You don't need to query Opportunity, query Account based on Ids present in Opportunity AccountId. We need Account fields.
    – Ashwani
    Commented Dec 22, 2016 at 21:21
  • more precisely, in your first sentence: In Trigger.new, you cannot reference relationship ...
    – cropredy
    Commented Dec 23, 2016 at 2:25
0

It looks like you have to query your Account records, don't think you can reference Account attributes from the record returned by Trigger directly

You must log in to answer this question.

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