I'm creating my first trigger (i'm an admin). It creates a new custom object,StakeholderContact every time a contact is created where 1-4 boxes are checked in the contact record. Right now I’m focused on the after insert portion, will do the after update part after I get the after insert working right (open to suggestions on that part too though). The trigger currently does what it’s supposed to IF 1 of the 4 boxes is checked but it does NOT create multiple new StakeholderContacts if more than 1 box is checked. I understand due to the if statement it’s stopping at whatever box is checked first that it hits & never goes beyond that. My question is, what should the loop/trigger look like so that it creates 4 new StakeholderContacts if all 4 boxes are checked in the contact record (tried for (Integer i = 0; i < 5; i++) so it would run 4 times but again understand why that’s not right, just not sure what is)? Also, if I run it 4 times how do I make sure I don’t end up with more than 4 records if all boxes are checked? Also open to any suggestions on basic trigger stuff I got wrong...Thanks in advance!
trigger CreateStakeholderContact on Contact (after insert, after update) {
//trigger purpose is to create new Key Buyer records connected to contacts & the Attack plans when new or existing contacts have the buyer box(es) ticked
//every trigger has this loop & a list to hold all new records
List<StakeholderContact__c> newkeybuyers = new List<StakeholderContact__c> ();
//go through the list of contacts and get all the related plans
//the map to hold all related plans for these contacts
Map <Id, THE_Prospect_Plan__c> Plans = new Map <Id, THE_Prospect_Plan__c>();
// go through the list of plans and add data into the map
{
For (THE_Prospect_Plan__c Plan : [select id from THE_Prospect_Plan__c where Id in :Plans.keyset ()])
{
Plans.put (Plan.Id, Plan);
}
//Go through the list of contacts and create the stakeholders to write
for (Contact C: Trigger.new) {
//which contacts are we using, only contacts where a buyer field is true & plan id is not null
If (C.ContPlanID__c != null && ((C.BuyerEconDMaker__c == true) || (C.ContactCoach__c == true) || (C.ContProcurementBuyer__c == true) || (C.ContTechnical_Buyer__c == true))){
//create a keybuyer
StakeholderContact__c Keybuyer = new StakeholderContact__c ();
//set the values
Keybuyer.THE_Prospect_Plan__c = C.ContPlanID__c;
Keybuyer.ContactPlan1__c=C.Id;
if (C.BuyerEconDMaker__c == true){
KeyBuyer.KeyBuyerType__c = 'Economic Decision-Maker';}
if (C.ContactCoach__c == true){
KeyBuyer.KeyBuyerType__c = 'Coach';
}if (C.ContProcurementBuyer__c == true){
KeyBuyer.KeyBuyerType__c = 'Procurement';
}if (C.ContTechnical_Buyer__c == true){
KeyBuyer.KeyBuyerType__c = 'Technical';
}
//stick the Keybuyer into the list we created earlier
newkeybuyers.add (Keybuyer);
}
// Save the key buyers
Insert NewKeybuyers;
}
}
}