Development questions

Write a trigger to create N number of child Contact records based on the value specified in the Number_of_Locations__c field on Account.

DevelopmentMediumCognizantTCSMindtree

Use after insert (Ids needed for the parent link) and create N child Contacts per Account.

apex
trigger AccountTrigger on Account (after insert) {
    List<Contact> cons = new List<Contact>();
    for (Account a : Trigger.new) {
        Integer n = a.Number_of_Locations__c == null ? 0 : (Integer) a.Number_of_Locations__c;
        for (Integer i = 1; i <= n; i++) {
            cons.add(new Contact(LastName = a.Name + ' Location ' + i, AccountId = a.Id));
        }
    }
    if (!cons.isEmpty()) insert cons;
}

Watch the 10,000 DML row limit if the number is large.

apex-triggertriggercodingscenario