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
Siana DcruzSiana Dcruz 

How to write trigger to create contact?

hey all,

i need help in my trigger. I have a object:additional_contacts__c
it has a field contact__c which is a lookup to Contact object.
if the users cannot find any contacts then they have to create one contact.

I have no good experience working on triggers.Can anyone please help me how to write a trigger for this
UC InnovationUC Innovation
Hi Siana,

Triggers can be tricky to learn at first. Try reading up on them in the documentation ( For your situation I recommend doing something like this.
trigger AdditionalContactsTrigger on Additional_Contacts__c (before insert) {
	Map<Additional_Contacts__c, Contact> noStandardContacts = new Map<Additional_Contacts__c, Contact>();
	for(Additional_Contacts__c additionalContact:{
		// Determine for which records the user 
		// could find no contacts for
		if (additionalContact.Contact == null) {
			// create the new contact
			Contact newContact = new Contact();
			// fill in fields
			// map it to use later
			noStandardContacts.put(additionalContact, newContact);
	// insert the newly created contacts
	insert noStandardContacts.values();
	// associate the custom contacts with the newly inserted standard ones
	for (Additional_Contacts__c key : noStandardContacts.keySet()) { = noStandardContacts.get(key).Id;

This is a template/example of what you can do without any knowledge of required fields and other triggers in your org.

Hope this helps!