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
Forcedotcom737Forcedotcom737 

Trigger to create contact based on custom object Attendee details. Help modify code.

Trying to learn apex by attempting to write simple triggers.

Could you please review the code below and suggest changes so First Name & Last Name (common fields between attendee and contact) information is copied over to the contact object when a new attendee is created in the custom attendee object. Also I couldnt find the field names for first name and last name in the contact object (Contact>Fields). Had to comment out a few lines to allow the code to compile. The division field is a custom field on both attendee and contact.


trigger CreateContact on Attendee__c (after insert, after update) {

List <Contact> contactToInsert = new List <Contact>();
for(Attendee__c at :Trigger.new){

Contact c = new Contact();

c.Division__c = at.Division__c;

//c.First Name = at.First_Name__c; // couldnt fin field name in the contact object. Found Field label.
//c.Last Name = at.Last_Name__c;

//contactToInsert.add(at); //compile error

}

insert contactToInsert;

}
Best Answer chosen by Forcedotcom737
Zuinglio Lopes Ribeiro JúniorZuinglio Lopes Ribeiro Júnior
Hello,

First of all, let me tell you that you are doing great! You're on the right direction.

There is a white space between the FirstName and LastName Contact's fields that why you are probably getting an error and you are trying do add to your Contact list a Attendee object (contactToInsert.add(at)) instead of a Contact (contactToInsert.add(c))

Try the code below:
 
trigger CreateContact on Attendee__c (after insert, after update) {

	List <Contact> contactToInsert = new List <Contact>();
	
	for(Attendee__c at : Trigger.new) {

		Contact c = new Contact(
							Division__c = at.Division__c,
							FirstName =  at.First_Name__c,
							LastName = at.Last_Name__c
							);

		contactToInsert.add(c); //compile error

	}

	Database.insert(contactToInsert);

}

Regards.

Don't forget to mark your thread as 'SOLVED' with the answer that best helps you.