I am new to apex and have wrote a trigger on the lead object that updates fields on the record, and also creates tasks associated with the record.
I have set up the code for both of these requirements to the best of my ability but am stuck on the appropriate use of 'before/after' in the trigger.
How do I structure the code to incorporate both the before and after aspect of this requirement. Here is what I have so far.
trigger KeyFieldsPopulated on Lead (before insert, before update) {
for (Lead l : Trigger.New) {
//Create list to store key fields
List<String> KeyFields = new List<String>();
KeyFields.add(l.FirstName);
KeyFields.add(l.LastName);
KeyFields.add(l.Email);
KeyFields.add(l.Phone);
KeyFields.add(l.Website);
KeyFields.add(l.Title);
//Create list to store key fields that have a value
List<String> KeyFieldsPopulated = new List<String>();
//Create a counter variable to track how many key fields have a value
Integer counter = 0;
//Loop through the key fields
for (Integer i = 0; i<KeyFields.size(); i++) {
if (KeyFields[i]!=null) {
KeyFieldsPopulated.add(KeyFields[i]);
counter = counter + 1;
}
l.Key_Fields__c = counter;
}
//Loop through the populated key fields and create a task
if (counter >= 3) {
for (Integer j = 0; j < KeyFieldsPopulated.size(); j++) {
Task t = new Task();
t.Subject = 'Verify the '+ KeyFieldsPopulated[j] + ' field';
t.WhatId = l.Id;
}
}
}
}