1

I have created a trigger that will create a child record when one picklist is field is updated 'Value1' in parent object.

But every time if Piclist is updated to "Value1" child record is created. I want to create child record only once? No Matter how many times we update Parent object to "value1"

trigger AutoCreateInterviewer on Position__c (after update) {
    List<Interviewer__c> interviewers = new List<Interviewer__c>();

    for (Position__c newPosition: Trigger.New) {
        if (newPosition.Hiring_Status__c  == 'Value1') {
            interviewers.add(new Interviewer__c(
                        Name = '1',
                        Position__c = newPosition.Id,
                        Employee__c = newPosition.Hiring_Manager__c,
                        Role__c = 'Managerial'));
        }
    }
    insert interviewers;
}

1 Answer 1

3

Add one more condtition, that checks if current parent already has child record. Ids of parent records, that already have child are stored in parentIdsWithChildSet variable.

trigger AutoCreateInterviewer on Position__c (after update) {
    List<Interviewer__c> interviewers = new List<Interviewer__c>();

    Set<Id> parentIdsWithChildSet = new Map<Id, Position__c>([
        select Id
        from Position__c
        where Id in (
            select Position__c
            from Interviewer__c
            where Position__c != null
            )
        ]).keySet();

    for (Position__c newPosition: Trigger.New) {
        if (newPosition.Hiring_Status__c  == 'Value1' && !parentIdsWithChildSet.contains(newPosition.Id)) {
            interviewers.add(new Interviewer__c(
                        Name = '1',
                        Position__c = newPosition.Id,
                        Employee__c = newPosition.Hiring_Manager__c,
                        Role__c = 'Managerial'));
        }
    }
    insert interviewers;
}
1
  • If the relationship is a master-detail, you could also add a roll-up summary field counting the child records and use that as a filter. Sep 14, 2017 at 7:50

You must log in to answer this question.

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