function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
raysfdc1988raysfdc1988 

trigger to avoid multiple child records for its parent record.

Hi All,

Lemme expalne in detail..
There two  objects called Case(Master parent) and Logsheet(child)

Say there are 3 cases...
caseA
CaseB
CaseC

now i should create only one child record for each parent case record..
Means.. for caseA , only one logsheet1(record of Logsheet)
              
Means for one CASE ID i should not create multiple Logsheet records,...
Please hlep to to write a trigger to avoid this duplication....

                    
                  
Best Answer chosen by raysfdc1988
ShashForceShashForce
Here's an example validation formula:

AND ( ISNEW() , parentobject__r.rollupfield__c > 0 )

All Answers

logontokartiklogontokartik
Please try this, excuse typos

trigger restrictLogSheet on LogSheet__c (before insert) {

    Set<Id> caseIds = new Set<Id>();
    for(Logsheet__c lg : Trigger.new){
          caseIds.add(lg.Case__c); // Get all the Case ids into Set
    }
    // Build a CaseMap. 
    Map<Id,Case> caseMap = new Map<Id,Case>();
    for(Case cs : [Select Id, CaseNumber, (Select Id,Name from LogSheets__r) from case where Id in :caseIds]){
        caseMap.put(cs.Id,cs);
    }
    // Iterate over the LogSheet to check and generate error
    for(LogSheet__c lg : Trigger.new){
        if(caseMap.containsKey(lg.Case__c)){
            if(caseMap.get(lg.Case__c).LogSheets__r != null && caseMap.get(lg.Case__c).LogSheets__r.size()>0){// If greater than 0, throw error
                lg.addError('Cannot add Log Sheet for the Case ' + caseMap.get(lg.Case__c).CaseNumber + ' There is already one present ' + caseMap.get(lg.Case__c).LogSheets__r[0].Name);
            }
        }
    }
    
}

If you dont want to go the code way, maybe you can try adding a rollup summary field and validation rules. 


ShashForceShashForce
You can achieve this without a trigger as well.

1.) Create a roll-up summary field on parent object to count number of child records.
2.) Write a validation rule on child object to avoid creation when the field on the parent is greater than zero.
raysfdc1988raysfdc1988
Thank you very much logontokartik...I will try it...

But using validation rule also sounds good...

Ok I can create roll-up summary field on parent object..
But how to write a validation on child object..

Say I have created LogshhetCount(rollup field on parent object)
then how to validate it on child object Logsheet
raysfdc1988raysfdc1988
Thanks Shashank_SFDC..
Please help me to write validation rule
ShashForceShashForce
Here's an example validation formula:

AND ( ISNEW() , parentobject__r.rollupfield__c > 0 )
This was selected as the best answer