[SalesForce] How to create required Master-Detail Records before insert

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:

  1. Create Contact Record
  2. 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:

  1. Fill out Registration Record and hit save.
  2. Apex Trigger automatically creates the appropriate Contact Record.
  3. Apex Trigger populates the Registered Contact Master-Detail field on the Registration Record with the newly created contact.
  4. Registration Record saves successfully with all required fields populated.

Thanks for your help!

Best Answer

You thought on looking for appropriate contact in before trigger, create if not exist and assign to Registration record is in the right direction. That concept should work fine. However few issues with your code/question.

  1. In the before insert trigger, you are already in the process of inserting Registration__c records. So no need to do this again.

    listreg.add(reg); insert listreg;

  2. Else block, is empty block. I think you intended to put above code in there, but it is not required. So you can remove this block altogether.

    else {}

  3. Try to query for contacts outside of the for loop so you will not run into Salesforce Limits.

Related Topic