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

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...

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
Here's an example validation formula:

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

All Answers

Please try this, excuse typos

trigger restrictLogSheet on LogSheet__c (before insert) {

    Set<Id> caseIds = new Set<Id>();
    for(Logsheet__c lg :{
          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]){
    // Iterate over the LogSheet to check and generate error
    for(LogSheet__c lg :{
            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. 

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.
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
Thanks Shashank_SFDC..
Please help me to write validation rule
Here's an example validation formula:

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