My requirements are:
- Upon creation of Accounts there is a trigger that creates a contact with specific record type
Organization Donor Proxy
- I wanted to create another trigger on Account after Insert/Update that will update a field
Aaron_Contact_id__c
with theAaron_Account_id__c
Trigger
trigger Account_UpdateDonorProxyTrigger on Account (after insert, after update) {
Contact[] dpContact = new list<Contact>(); // donor proxy contact
try{
Map<id, account> acctMap = Trigger.newmap;
//for (Account acct : trigger.new){
System.debug('account ids >>> :' + acctMap.keyset());
// Get all the contacts against each AccountId
for (Contact cnt: [SELECT contact.id, contact.accountid, contact.name, contact.Aaron_Contact_Id__c, contact.RecordType.Name
FROM Contact
WHERE Contact.accountid IN: acctMap.keyset() ]){
System.debug('Contact record type <<< :' + cnt.RecordType.Name);
if(cnt.RecordType.Name == 'Organization Donor Proxy'){
cnt.Aaron_Contact_ID__c = acctMap.get(cnt.accountid).Aaron_Account_ID__c;
dpContact.add(cnt);
}
} // end of for loop
//}
update dpContact;
}
catch (exception ex){
System.Debug('stack trace string:::' + ex.getStackTraceString() );
}
}
Question
Does this trigger comply with the apex best practices? Am I missing something or anything that can be improved? What are the best practices and pitfalls in triggers anyways.
Best Answer
After searching here and there and writing few triggers myself, I have come up with the following:
On/Off
.Active/Inactive
, you would need to make the changes on sandbox and then push it from their using changeset or IDE. Using custom settings to make a decision on the trigger will make life easy.Helpful links: https://developer.salesforce.com/page/Trigger_Frameworks_and_Apex_Trigger_Best_Practices http://www.iterativelogic.com/salesforce-apex-trigger-best-practices/ http://krishhari.wordpress.com/2013/07/22/an-architecture-framework-to-handle-triggers-in-the-force-com-platform
https://developer.salesforce.com/page/How_to_Write_Good_Unit_Tests https://developer.salesforce.com/blogs/developer-relations/2015/01/apex-best-practices-15-apex-commandments.html https://developer.salesforce.com/page/Trigger_Frameworks_and_Apex_Trigger_Best_Practices