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
John 98778John 98778 

before insert trigger

how to write trigger ,it should'nt allow more than 2 contacts for a single account
Muneendar POC 6Muneendar POC 6
Please check the below trigger and Helper class
trigger ContactTrigger on Contact (before insert) {
    if(trigger.isInsert && trigger.isBefore){
        for(contact con:trigger.new){
            boolean contactcountval=ContactHelper.Countcontact(trigger.new);
            if(!contactcountval){
                con.adderror('Account should have only two Contacts');
            }
            
        }
    }
    
}



public class ContactHelper {
    Public static boolean Countcontact(list<contact> newConValues){
        set<Id> accid=new set<id>();
        for(Contact con: newConValues){
            accid.add(con.accountid);  
        }
        list<contact> conList=[select id from contact where accountid In:accid];
        if(conList.size()<2)
            return true;
        return false;
    }
    
}

Please select this solution as best answer if your solution is resolved.Let me know if any issues 
Pruthvi KankunthalaPruthvi Kankunthala
Try this code 
trigger conTrigger on Contact (before insert) {
    if(trigger.isInsert && trigger.isBefore){
      contactTriggerHelper.allowTwoContacts(trigger.new);
    }
    
}


public class contactTriggerHelper {
    Public static boolean allowTwoContacts(list<contact> newConValues){
        set<Id> accid=new set<id>();
        list<contact>conlist=new list<contact>();
		list<account>acclist=new list<account>();
	
        for(Contact con: newConValues){
            accid.add(con.accountid);  
        }
        
        acclist=[SELECT id,name FROM account WHERE id in:accid];
		conlist=[SELECT id,name,accountid FROM contact WHERE accountid in:accid];

		for(account acc:acclist){
		listcon.clear();
		Integer i=0;
			for(contact tmpCon:conlist){
				if(tmpCon.accountid==acc.id){
				listcon.add(tmpcon);
				i++
				}
			}
		if(i==2 || i>2)
		         tmpCon.adderror('Account should have only two contacts');
        }         
}

Let me know in case of any issues . Please mark as a best answer if problem solved . Cheers !!!