I need to create a trigger on Contact that is triggered after insert or after update. I have two custom fields. One in Account called 'Primary Contact' which is text field and one in Contact called 'Primary' which is checkbox. When a new Contact is added or updated, my trigger needs to check if the checkbox has been checked(to true) and update the corresponding Account's 'Primary Contact' to the Contacts 'Owner' field. If possible I would greatly appreciate what each line of code is doing. I've seen many examples but they don't explain whats happening. If possible it would be great to see a very simple version.
EDIT: Sorry I made a mistake.Its not suppose to be the 'Owner' field but the 'firstname' and 'lastname' fields in Contact.
trigger UpdatePrimaryFieldInAccount on Contact (after insert, after update) {
//create list to hold accounts
List<Account> accList = new List<Account>();
//Get related Accounts for the contact in this trigger
Map<Id, Contact> contactWithAccount = new Map<Id, Contact>([SELECT Id,(SELECT Id FROM Account) FROM Contact WHERE Id IN :Trigger.New]);
//iterate through each contact
for(Contact c : Trigger.New) {
if(c.Primary__c) //if custom field is checked
//change/update Account Primary Contact field
contactWithAccount.get(c.Id).Primary_Contact__c= c.Owner;
//add to accList
accList.add(c.accountId);
}
//finally update the accList in the database
update accList;
}