Thursday 13 October 2016

Apex - create master-detail records

master(parent) - account

detail(child) - contact


 Creating a Child Record When a Parent Record is Created

You want to automatically create a new child record when you create a parent record. The child record should be populated with default values from contact.


trigger AutoCreatecontact on account (after insert) {
    List<contact> cons = new List<contact>();

  
    for (account newacc: Trigger.New) {
        if (newacc.customfield__c != null) {
            cons.add(new contact(
                        Name = 'Iain',
                        account = newacc.Id,
                        contactcustomfield__c = newacc.customfield__c,
                        another_contactcustomfield__c = 'Yes'));
        }
    }
    insert cons;
}


No comments:

Post a Comment