0

I have an Approval Process, myApprovalProcess, that has multiple steps (total of 4) where different users are needed for approving a record. At each step, a different user will need to approve/reject and I need to fetch the original submitter's id regardless of what step it is in. The approval process performs some field updates on an Account as part of the Approval/Rejection.

Question:

How can I fetch in an apex trigger the original user who placed the record into the approval process?

What we tried but didn't work:

trigger MyTrigger on Account (after update) {
  Set<Id> accountIdSet = new Set<Id>();
  for(Account acnt : Trigger.new) {
     accountIdSet.add(acnt.Id);
  }

  // this returns all ProcessInstances records 
  List<ProcessInstance> processInstanceList = [select CreatedBy.Id, SubmittedById, TargetObjectId from ProcessInstance where TargetObjectId IN :accountIdSet];
}

Issues we are facing

  1. When retrieving ProcessInstance records, if the record has gone through steps 1-3, then the SubmittedById is always set to the last user's id who last approved/rejected the record on all ProcessInstance records.
  2. For every step that has been completed, an additional ProcessInstance record is created for each Account so it is not as simple as fetching the ProcessInstance record.

Goal(s)

  1. Retrieve only the original submitter id, not the last user to submit an approval/reject
  2. fetch this on afterUpdate event of an Account
  3. I want the user id for the person who caused the record to go into the approval process

1 Answer 1

0

have you tried doing it the other way around? querying for Accounts and only get the ProcessInstance you need?

With a sub-query you could sort the way you want and limit the results to 1 per record, making it much easier to find

trigger MyTrigger on Account (after update) {

  List<Account> accounts = [
    SELECT 
      Id, 
      (
        SELECT OriginalActorId, CreatedById 
        FROM ProcessSteps
        ORDER BY CreatedDate
        LIMIT 1
      ),(
        SELECT SubmittedById
        FROM ProcessInstances
        ORDER BY CreatedDate
        lIMIT 1
      )
    FROM Account
    WHERE Id IN :Trigger.New // or :Trigger.NewMap.keySet()
  ];

  // in there you'll have a list of Accounts with a list of 1 (or 0) ProcessInstanceHistory / ProcessInstance record. Then you can check which field you want to keep ;)
}

You must log in to answer this question.

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