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.
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
More Development questions
- What is an Apex Trigger in Salesforce and when should you use it over Flows?
- What is the difference between before triggers and after triggers?
- Explain all Trigger context variables (isInsert, isUpdate, isDelete, isUndelete, isBefore, isAfter, isExecuting, size, operationType).
- What is the difference between Trigger.new and Trigger.old?
- In which trigger events are Trigger.new and Trigger.newMap available?
- In which trigger events are Trigger.old and Trigger.oldMap available?