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
Priyanka DumkaPriyanka Dumka 

Trigger whenever a record is inserted to the account automatically insert to the contact and throw error if contact is more than 5.

Trigger whenever a record is inserted to the account automatically insert to the contact and throw error if contact is more than 5.
Best Answer chosen by Priyanka Dumka
Shri RajShri Raj
trigger CreateContact on Account (before insert) {
    for (Account acc : Trigger.new) {
        List<Contact> relatedContacts = [SELECT Id FROM Contact WHERE AccountId = :acc.Id];
        if (relatedContacts.size() >= 5) {
            acc.adderror('Cannot create more than 5 Contacts for an Account');
        } else {
            Contact con = new Contact();
            con.LastName = acc.Name;
            con.AccountId = acc.Id;
            acc.Contacts.add(con);
        }
    }
}

 

All Answers

SubratSubrat (Salesforce Developers) 
Hello Priyanka ,

Requesting you to take reference from this similar discussion and let me know further if you are facing error 

-> https://stackoverflow.com/questions/71153247/restrict-more-then-2-contacts-that-saved-on-account-object

Hope it helps !
Thank you.
Shri RajShri Raj
trigger CreateContact on Account (before insert) {
    for (Account acc : Trigger.new) {
        List<Contact> relatedContacts = [SELECT Id FROM Contact WHERE AccountId = :acc.Id];
        if (relatedContacts.size() >= 5) {
            acc.adderror('Cannot create more than 5 Contacts for an Account');
        } else {
            Contact con = new Contact();
            con.LastName = acc.Name;
            con.AccountId = acc.Id;
            acc.Contacts.add(con);
        }
    }
}

 
This was selected as the best answer