I'll start off by saying I'm a complete noob to Salesforce and Apex Triggers.
What we've done so far is added a custom Email field to the Account Record. Account records are automatically created via external integration (magento store customers).
We also have Contact records that are created automatically from a different external integration (zendesk).
What we want to happen is when a new Account is created, all of the Account information will be transferred onto the the Contact record if a record exists with the same email, if a Contact doesn't exist, it will create a New Contact with all of the same Account information.
I'm thinking this needs to be done with some sort of upsert trigger whenever a new Account is created / updated?
EDIT, here is the current trigger I'm using:
trigger UpsertTrigger on Account (after insert, after update) {
List<String> listAccountEmails = new List<Account>();
//capture all the account email updated
for( Account a : Trigger.new )
{
listAccountEmails.add(String.Valueof(a.Email));
}
//Get all the related contacts match email address
List<Contact> listContacts = new List<Contact>();
listContacts = [SELECT Id, FirstName, LastName, Email FROM Contact WHERE Email in :listAccountEmails];
//Convert list Contacts into map with email as key
Map<String, Contact> mapContacts = Map<>(String, Contact);
for ( Contact c : listContacts)
mapContacts.put(c.Email, c);
// Loop thru account emails and create contact record if email doesnot exist or //update contact if exist
for (String e : listAccountEmails) {
if (mapContacts.isContainsKey(e) == true) {
//Map Account fields to Contact fields
a.Last_Name__c = c.LastName,
a.First_Name__c = c.FirstName,
a.Magento_Customer_ID__c = c.Magento_Customer_ID__c,
a.Sales_Rep__c = c.Sales_Rep__c,
a.id = c.AccountId,
a.Email__c = c.Email)
}
else
//Create New Contact
Contact con = new Contact();
con.LastName = a.Last_Name__c;
con.FirstName = a.First_Name__c;
con.Magento_Customer_ID__c = a.Magento_Customer_ID__c;
con.Email = a.Email__c;
con.Sales_Rep__c = a.Sales_Rep__c;
con.AccountId = a.id;
insert con;
}
upsert Contacts;