+ Start a Discussion
Ad.baylesAd.bayles 

Help with Trigger : Create a child record linked to another parent object

Hello all,

I rely on your help on this 'cause I am real noob in Apex code! My usecase is quite simple, but I can't get though it : I would like a child record to be created ("Registration")  on a lead insert or update.

 

This custom object is linked to another parent object, "Session".

 

Leads and Sessions are not directly linked to each other, but through the Registration object. This allows a many-to-many relationship between both parents.

On both parents I have a "Form ID" field, which is a numeric field (the value of this field is unique on the Session Object).

 

My point is that the Registration must be linked to the Session where the Form Id matches the Lead Form ID field, so I need to create a List that will check on all the Session records for that value

 

 

This is my trigger on lead :

 

trigger AutoCreateRegistration on Lead (before insert, before update) {
    List<Registration__c> createregistration = new List <Registration__c> {};
  


for (Lead lead : trigger.new) {

   if (lead.Lead_Source_2__c == 'Event' && lead.Form_Id__c != null)



createregistration.add(new Registration__c
(
 RecordTypeId = '012M00000000BHh',
 Session__c = '?',
 Lead__c = lead.Id

 ));

        }
    }

try {
insert createregistration ;
}
catch (Exception Ex)
{
system.debug(Ex);
}
}

 

 

 

Does anyone know how I can create a loop for this ?

hchhch

Change the select query from WHERE Form_ID__c = Lead__c.Form_ID__c to

" WHERE Form_ID__c =lead.Form_ID__c"