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
nani reddy 3nani reddy 3 

how to write a trigger an account having not more then 2 child records

please help me with that one.
i am trying to post my code 
ManojjenaManojjena
H Nani,

Do you want to write a trigger that it should give error when some one will enter the third chid record for a specific account ? Please confirm so that we can help you .
What is your child object ? 

 
sagar patil 13sagar patil 13
Write a before trigger on Contact
1.Fetch Account Id of contact which is going to insert or update
2.Fetch contact list of Account
List<Account> accList=[select Id, (select Id from contacts)
                                     from Account
                                     where Id = :accountIdOfContact].....................accountIdOfContact retreived in step 1
3.List<Contact> accountConList = accList[0].contacts;
4.if(accountConList .size() >= 2)
 {
      show error message
}
 
Lalit Mistry 21Lalit Mistry 21
Hi Sagar,

Below code should work for you.
Ensure trigger is executed after insert/update.
trigger ContactTrigger on Contact (after insert, after update) {
    Map<Id, Set<Contact>> accountVsContacts = new Map<Id, Set<Contact>>();
	for(Contact con : Trigger.new){
		if(!accountVsContacts.containsKey(con.AccountId)){
			accountVsContacts.put(con.AccountId, new Set<Contact>());
		}
		accountVsContacts.get(con.AccountId).add(con);
	}
	
	List<Account> relatedAccounts = [SELECT Id, (SELECT Id FROM Contacts) FROM Account WHERE Id IN :accountVsContacts.keySet()];
	for(Account act: relatedAccounts){
		if(act.Contacts.size() > 2){
			for(Contact con : accountVsContacts.get(act.Id)){
				con.addError('Account is already associated with 2 contacts.');
			}
		}
	}
}

Mark this as best answer if it helps.
ManojjenaManojjena
Hi ,

What I feel it should not be in update ,and it should before insert else we need to skip the current record for account ,means you need to remove the current record from the query .