function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
OcoBriOcoBri 

After Insert Trigger to create child record

Contacts have a lookup relationship to a custom Worker__c object.

Whenever a new Worker__c record is created, I want to create an associated (child) Contact.

My code is as follows:

trigger NewContactforWorker on Worker__c (after insert) {
	List<Contact> conList = new List<Contact>;
    for (Worker__c wkr : trigger.new) {
        a = new Contact(Worker__c = wkr.Id, FirstName = wkr.First_Name__c, 
                        LastName = wkr.Last_Name__c, QSAC_external_id__c = wkr.Worker_External_ID__c);
        conList.add(a);
    }
    insert conList;
}

But I get an error in between the second and third lines.  Can anyone help?

Thank you.
Best Answer chosen by OcoBri
rohitsfdcrohitsfdc
OcoBri,
Please change your code to the code below

trigger NewContactforWorker on Worker__c (after insert) {
	List<Contact> conList = new List<Contact>();
    for (Worker__c wkr : trigger.new) {
//initialize a new contact
        Contact a = new Contact(Worker__c = wkr.Id, FirstName = wkr.First_Name__c, 
                        LastName = wkr.Last_Name__c, QSAC_external_id__c = wkr.Worker_External_ID__c);
        conList.add(a);
    }
if(conlist.size()>0){
try{
    insert conList;
}catch(DMLException e){
//handle  your exception here
}
}
}


All Answers

John WestenhaverJohn Westenhaver
What's the error?
OcoBriOcoBri
The error is on line 2: unexpected token: ';'
ForceWaveForceWave
Change you 2nd line as below

List<Contact> conList=new Lits<Contact>();
rohitsfdcrohitsfdc
OcoBri,
Please change your code to the code below

trigger NewContactforWorker on Worker__c (after insert) {
	List<Contact> conList = new List<Contact>();
    for (Worker__c wkr : trigger.new) {
//initialize a new contact
        Contact a = new Contact(Worker__c = wkr.Id, FirstName = wkr.First_Name__c, 
                        LastName = wkr.Last_Name__c, QSAC_external_id__c = wkr.Worker_External_ID__c);
        conList.add(a);
    }
if(conlist.size()>0){
try{
    insert conList;
}catch(DMLException e){
//handle  your exception here
}
}
}


This was selected as the best answer
OcoBriOcoBri
Thank you all.  Now I can try to write the test class :)