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
trudd1.390604290929309E12trudd1.390604290929309E12 

Cross Object field update trigger

I posted something similar to this a couple weeks ago but I didn't explain myself clearly so I'm trying again.  I'm an administrator new to Apex and am having difficulties writing (what should be) a simple trigger.  I have a custom object that logs research requests the BD team has for upcoming Opportunities (a one to many relationship).  I'd like to create a trigger so that when the Opportunity is closed the status field on the reasearch request custom object (a picklist field) is updated in each research request to "Closed."  When the status opf each request is changed to "Closed" a workflow sends an email alert to the research team that the request is closed.  I'd like the process to work this way because it will also allow the BD person or the researcher to manually close one of the requests while leaving the others open.  The trigger should update the status to "Closed" for all the request records if Opportunity.IsClosed = TRUE which should fire the workflows on the custom object.

Any direction with this issue is appreciated.

Thank you.
Tim
Cloud_BKCloud_BK
Hi Tim,

I'm also fairly new to Apex but hopefuly I can help out and break it out into steps for how your trigger should operate.

Step 1)
Since the logic in your trigger is going to be based on an field update to a triggered record, this should be an "After Insert, After Update" trigger.

Step 2)
Create a List of Opportunities that that your trigger is running (1 or up to 200 if you are loading them).  Use a for loop with an if statement to only add Opportunities that have a status of only closed
Example:

List<ID> closedOpps = new List<ID>();
  for (Opportunity Opp : Trigger.old) {
    if (Opp.Status = 'Closed') {
      closedOpps.add(Opp.ID);    }
  }

Step 3)
Now that we have a list of updated opps, you need to query all the related Research Requests that have an Opp contained in the list above
Example:
List<Research_Request__c> ClosedRR= [SELECT Id, Opportunity__r.id FROM Research_Request__c
                           WHERE Opportunity__r.id IN :Opps]
 
Step 4) Now we have all the Res Req that should be updated, lets update them

for ( Research_Request__c RRtoupdate : ClosedRR){
RRtoupdate.status__c = 'Closed';}

Step 5) Insert these newly updated Res Reqs to the database

Insert RRtoupdate;

Good Luck, Cheers.

BK