0

I am creating a case record in parent obj after trigger. There is a lookup field on parent object which is related to Case object and I want to update this.

Field Name: RelationshipToCase
Field Type: Lookup
Related To: Case

Here's my code in Parent Object Trigger Handler:

protected override void afterInsert(){
    createCase();
}
    
private static void createCase(){
    List<Case> casesCreated = new List<Case>();
    Id caseRecTypeId = Schema.SObjectType.Case.getRecordTypeInfosByDeveloperName().get('Case Rec Type').getRecordTypeId();
    
    for(ParentObj par: newList) {
        case myCase = new Case();
        myCase.RecordTypeId = caseRecTypeId;
        myCase.Status = 'New Case';
        myCase.Origin = 'Parent object case';
        myCase.OwnerId = UserInfo.getUserId();
        casesCreated.add(myCase);
    }
    
    insert CasesCreated; 
    
    //Now, I need to get the ID of the Case created and update RelationshipToCase field// 
    // ??? //
} 

1 Answer 1

2

You can actually use a before insert trigger for this. This has much better performance than doing it after insert, because you don't need to save your data "twice", as it were.

As far as solving your problem, remember that Lists are ordered, which means wherever you put something, it will stay in that spot until you do something to move it. That means you can write your code like this:

Case[] newCases = new Case[0];
for(Object__c parent: newList) {
  // For brevity, do what you need to do here //
  newCases.add(populateCaseFor(parent));
}
insert newCases;
// Option 1, remove from list as you move through parents
for(Object__c parent: newList) {
  parent.RelationshipToCase__c = newCases.remove(0).Id;
}
// Option 2, use an indexed for loop:
for(Integer index = 0, size = newList.size(); index < size; index++) {
  newList[index].RelationshipToCase__c = newCases[index].Id;
}

By assigning a value to Trigger.new in a before insert trigger, the records will automatically be updated when the trigger ends.

2
  • How do I convert my code into Case[] at this line : newCases.add(populateCaseFor(parent)); Also, can you help me understand Option-1 , why are we removing newCases.remove(0).Id.
    – Jenina
    Nov 7, 2021 at 6:22
  • @Lucas We are iterating through each record, so we can remove the first item the case list in order. Try it out on paper, it should make sense. As far as populateCaseFor(Parent), it's just a placeholder for whatever it is you want to do with your case.
    – sfdcfox
    Nov 8, 2021 at 3:33

You must log in to answer this question.

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