To update a related record when a specific field is modified in a parent record using a trigger, you can follow these steps:
- Identify the relationship between the parent and child objects. This could be a lookup or master-detail relationship.
- Determine the specific field (let’s call it
SummerVacation__c
) You want to monitor for changes in the parent object. - Write a trigger on the parent object (let’s call it
School__c
) that executes after an update. - Inside the trigger, iterate over the trigger’s
Trigger.new
list to access the updated parent records. - Use the
Trigger.oldMap
to retrieve the previous values of the parent records. - Compare the specific field values of the old and new parent records to identify changes. You can use a
if
statement to check if the specific field has been modified. - If the specific field has been modified, retrieve the related child object (let’s call it
Student__c
)records based on the relationship between the parent and child objects. You can use SOQL queries or related fields to fetch the child records. - Modify the desired field(s) on the child records with the new values. You can assign new values directly or use a loop to update multiple child records.
- Finally, perform an update operation on the child records to persist the changes.
Here’s an example trigger code that demonstrates these steps:
trigger UpdateRelatedRecord on School__c (after update) {
Set<Id> parentIdsToUpdate = new Set<Id>();
List<Student__c> childRecordsToUpdate = new List<Student__c>();
for (School__c parentRecord : Trigger.new) {
School__c oldParentRecord = Trigger.oldMap.get(parentRecord.Id);
// Check if the specific field has been modified
if (oldParentRecord.SummerVacation__c != parentRecord.SummerVacation__c) {
parentIdsToUpdate.add(parentRecord.Id);
}
}
if (!parentIdsToUpdate.isEmpty()) {
// Retrieve related child records
List<Student__c> childRecords = [SELECT Id, SummerVacation__c FROM Student__c WHERE School__c IN :parentIdsToUpdate];
// Update desired field(s) on child records
for (Student__c childRecord : childRecords) {
childRecord.SummerVacation__c = true; // Update the SummerVacation__c field on the related record
childRecordsToUpdate.add(childRecord);
}
// Perform an update on child records
if (!childRecordsToUpdate.isEmpty()) {
update childRecordsToUpdate;
}
}
}
Write a trigger to count the number of related child records on the parent.
For any Queries/doubts comment below and for quick responses on LinkedIn and Twitter.