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
Nagarjun TNagarjun T 

every customer should have maximum two payment child records

Customer__c
     firstName__c
     LastName__c
     Phone__c
     Email__c
     Amount__c

Payment__c
        MOde__c
        Amount__c
        Customer__c  : Lookup(Customer)
Khan AnasKhan Anas (Salesforce Developers) 
Hi Nagarjun,

Greetings to you!

You can write a trigger for this. Please try the below code, I have tested in my org and it is working fine. Kindly modify the code as per your requirement.
 
trigger MaxTwoChild on Payment__c (before insert) {
    
    List<Id> cusId = new List<Id>();
    for(Payment__c p : trigger.new){
        if(p.Customer__c != null){
            cusId.add(p.Customer__c);    
        }
    }
    
    List<Payment__c> pList = new List<Payment__c> ();
    
    List<Customer__c> cusLst = [SELECT Id,(SELECT Id FROM Payments__r) FROM Customer__c WHERE Id IN : cusId] ;  // Payments__r is child relationship name, you can check it on Customer__c lookup field on payment object
    for(Customer__c cusObj : cusLst ){
        for(Payment__c pyt : cusObj.Payments__r){     
            pList.add(pyt);
        }
    }
    
    for(Payment__c per : trigger.new){ 
        if(pList.size() > 1 ) {  
            per.addError('You can not add more than two Payments for this Customer'); 
            
        }
    }
}

I hope it helps you.

Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future. It will help to keep this community clean.

Thanks and Regards,
Khan Anas