+ 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 (https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_triggers.htm). 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: Trigger.new){
		// 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()) {
		key.contact = 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!