function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
QuanchiQuanchi 

Apex Code for Trigger Help

Hello,

 

If you can help point me in the right direction, it would be a great help.

 

I need an Apex Trigger that updates opportunity #1 custom field #1 with the opportunity ID from Opportunity #2 when Opportunity #2 custom field #2 (lookup field for opportunity name) is populated with opportunity #1's ID.  Hope this makes sense.

 

Thanks,

Quanchi

SeAlVaSeAlVa

Have you taken into account that two different Opportunities might point to the same opportunity #1 ?

In that case, which ID would you store  in #1 ?

QuanchiQuanchi

That is a possiblity, but what were are doing is we could have a max of 2 opportunities associated with each other and we want it to automatically update the 2 opportunity when the first opportunity is associated with the other.

SeAlVaSeAlVa

it would be something similar to ..

 

 

trigger whatever on Opportunity(before update, before insert){
  Set<ID> newOpps = new Set<ID>();
  for(Opportunity o : trigger.new){
    if(o.field_with_the_lookup__c != null && newOpps.add(o.field_with_the_lookup__c);
  }

  Map<ID,Opportunity> toUpdateCandidates = new Map<ID,Opportunity>([select custom_field_to_update__c from Opportunity where ID in :newOpps]);
  Set<Opportunity> toUpdate = new Set<Opportunity>();
  for(Opportunity o : trigger.new){
    if(o.field_with_the_lookup__c != null ){
	  Opportunity candidate = toUpdateCandidates.get(o.field_with_the_lookup__c);
	  if(candidate.custom_field_to_update__c != o.ID){
        candidate.custom_field_to_update__c = o.ID;
        toUpdate.add(candidate);
      }
    }
  }
  if(toUpdate.size!=0){
    update toUpdate;
  }
}

 

 

I haven't check the syntax nor its functionality, but might be something similar to that.

 

Regards

QuanchiQuanchi

Thanks, this is a great start.  I am not good with syntax yet....I will keep trying.