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
saha dsaha d 

how to achieve below task

If the number of child records are more than 10, and if so avoid from creating one more child record.

Thanks adavance........
Best Answer chosen by saha d
Devanshu soodDevanshu sood

Another approch is to use trigger like

 

trigger restrictLogSheet on child (before insert) {

    Set<Id> parentIds = new Set<Id>();
    for(child lg : Trigger.new){
          parentIds.add(lg.parent__c); // Get all the parent ids into Set
    }
    // Build a parentMap. 
    Map<Id,parent> parentMap = new Map<Id,parent>();
    for(parent cs : [Select Id, parentNumber, (Select Id,Name from child__r) from parent where Id in :parentIds]){
        parentMap.put(cs.Id,cs);
    }
    // Iterate over the LogSheet to check and generate error
    for(child lg : Trigger.new){
        if(parentMap.containsKey(lg.parent__c)){
            if(parentMap.get(lg.parent__c).child__r != null && parentMap.get(lg.parent__c).child__r.size()>0){// If greater than 0, throw error
                lg.addError('Cannot add Log Sheet for the parent ' + parentMap.get(lg.parent__c).parentNumber + ' There is already one present ' + parentMap.get(lg.parent__c).child__r[0].Name);
            }
        }
    }
    
}
 

 

All Answers

Devanshu soodDevanshu sood

you can create a rollup feild on parent object which count child record and then use validation like

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

Mark it as best answer ,if it helps you.

Devanshu soodDevanshu sood

Another approch is to use trigger like

 

trigger restrictLogSheet on child (before insert) {

    Set<Id> parentIds = new Set<Id>();
    for(child lg : Trigger.new){
          parentIds.add(lg.parent__c); // Get all the parent ids into Set
    }
    // Build a parentMap. 
    Map<Id,parent> parentMap = new Map<Id,parent>();
    for(parent cs : [Select Id, parentNumber, (Select Id,Name from child__r) from parent where Id in :parentIds]){
        parentMap.put(cs.Id,cs);
    }
    // Iterate over the LogSheet to check and generate error
    for(child lg : Trigger.new){
        if(parentMap.containsKey(lg.parent__c)){
            if(parentMap.get(lg.parent__c).child__r != null && parentMap.get(lg.parent__c).child__r.size()>0){// If greater than 0, throw error
                lg.addError('Cannot add Log Sheet for the parent ' + parentMap.get(lg.parent__c).parentNumber + ' There is already one present ' + parentMap.get(lg.parent__c).child__r[0].Name);
            }
        }
    }
    
}
 

 

This was selected as the best answer