I have a custom Registration object with a Master-Detail lookup to a Contact Record (The Registered Contact). Often, when creating a new Registration Record the Contact record does not exist. The current process is:
- Create Contact Record
- Create Registration Record
I'm trying to automatically create the Contact Record based on information from the Registration Record and insert it into the database, then insert that Record ID into the Master-Detail Lookup.
The issue is, I can't save my Registration Record with the Master-Detail field blank. I thought because the trigger is "before insert" it would populate the Registered Contact lookup before the record was saved. There is obviously something I am not understanding.
This is my trigger (it's pretty ugly right now):
trigger CreateContactRecords on Registration__c (before insert) {
List<Contact> contactlist = new List<Contact>();
List<Registration__c> listreg = new List<Registration_2014__c>();
for (Registration__c reg : Trigger.new) {
List<Contact> c = [select FirstName, LastName from Contact WHERE FirstName = :reg.First_Name__c AND LastName = :reg.Last_Name__c];
if (c.size() == 0) {
Contact newc = new Contact();
newc.FirstName = reg.First_Name__c;
newc.LastName = reg.Last_Name__c;
newc.RecordType.ID = '012i00000002x32';
contactlist.add(newc);
insert contactlist;
reg.Registrant__c = newc.ID;
}
else {}
listreg.add(reg);
insert listreg;
}
}
To Summarize I would like the process to be:
- Fill out Registration Record and hit save.
- Apex Trigger automatically creates the appropriate Contact Record.
- Apex Trigger populates the Registered Contact Master-Detail field on the Registration Record with the newly created contact.
- Registration Record saves successfully with all required fields populated.
Thanks for your help!