scenario, child to parent trigger where child- case, parent-opportunity with lookup relation. There is a field named opcase in opportunity which is a read only field .Whenever the case status is changed or created it should reflect in opcase
trigger TriggerOnCase on Case (after insert, after update) {
CaseHandler handler = new CaseHandler();
if(Trigger.isAfter){
if(Trigger.isInsert){
handler.changeOppfield(Trigger.new);
}
if(Trigger.isUpdate){
handler.changeOppfield(Trigger.Old, Trigger.New);
}
}
}
public class CaseHandler {
public void changeOppfield(List<Case> newCases){
for(Integer i = 0; i<Trigger.size; i++){
if(newCases.get(i).Opportunity__c != null){
Opportunity opp = new Opportunity();
opp.Id = newCases.get(i).Opportunity__c;
opp.Opcase__c = 'Case status was changed';
update opp;
}
}
}
public void changeOppfield(List<Case> oldCases, List<Case> newCases){
for(Integer i = 0; i<Trigger.size; i++){
if(oldCases.get(i).Status != newCases.get(i).Status && newCases.get(i).Opportunity__c != null){
Opportunity opp = new Opportunity();
opp.Id = newCases.get(i).Opportunity__c;
opp.Opcase__c = 'Case status was changed';
System.debug('Opp is: '+opp);
System.debug('Opp is: '+opp.Opcase__c);
update opp;
}
}
}
}
The trigger fires on after insert and after update.
On after insert it passes the list of new Cases triggered to the handler method by using Trigger.New (Since these are new records, there won't be Trigger.old in this case.) On after update, it passes the list of both old and new Cases triggered to the handler method by using Trigger.Old and Trigger.New.
The changeOppfield method then checks if the particular Case is linked to the Opportunity or not. If it is linked and the Case status was changed, it updates the corresponding Opportunity's Opcase__c field.
Just replace the lines 11 and 26 (In Case Handler) with:
All Answers
Try the following code:
The trigger fires on after insert and after update.
On after insert it passes the list of new Cases triggered to the handler method by using Trigger.New (Since these are new records, there won't be Trigger.old in this case.)
On after update, it passes the list of both old and new Cases triggered to the handler method by using Trigger.Old and Trigger.New.
The changeOppfield method then checks if the particular Case is linked to the Opportunity or not. If it is linked and the Case status was changed, it updates the corresponding Opportunity's Opcase__c field.
Thanks a lot for the code. But the oppcase should show the status of the case like new or escalated or whatever it is changed to.
Just replace the lines 11 and 26 (In Case Handler) with:
If this helped you solve the problem, please mark it as the Best Answer.
Thanks.