We have a report that aggregates all of our leads based upon status. The person who actually cares about this data would like to distinguish between a converted (status: qualified) lead and a converted lead that had an opportunity associated with it (custom status: qualified with opportunity).
I wrote a simple afterUpdate
trigger which accomplishes this, however it doesn't work because you can't update a lead once it has been converted:
//Update the lead status if there is a related opportunity and the status hasn't previously been set
if (updatedLead.ConvertedOpportunityId != null && updatedLead.Status != STATUS_QUALIFIED_OPP) {
updatedLead.Status = STATUS_QUALIFIED_OPP;
update updatedLead;
}
I seemingly can't use a beforeUpdate
trigger because the ConvertedOpportunityId
hasn't been set so I don't know if there's a related opportunity.
Does anyone have an idea how I can accomplish changing the status once I know the lead has a related opportunity?
Edit
Here is the trigger:
trigger LeadTrigger on Lead (after delete, after insert, after undelete, after update, before delete, before insert, before update) {
LeadTriggerHandler handler = new LeadTriggerHandler(Trigger.size);
if(Trigger.isUpdate && Trigger.isAfter){
handler.OnAfterUpdate(Trigger.new);
}
}
And the OnAfterUpdate
method:
public void OnAfterUpdate(Lead[] updatedLeads) {
this.VerifyLeadStatus(updatedLeads);
}
public void VerifyLeadStatus(Lead[] updatedLeads) {
for (Lead updatedLead : updatedLeads) {
System.debug(updatedLead.Status + ' ' + updatedLead.ConvertedOpportunityId);
if(updatedLead.Status == 'Qualified' && updatedLead.ConvertedOpportunityId != null) {
updatedLead.Status.addError('You cannot use Qualified as a status value when creating an opportunity');
}
if(updatedLead.Status == 'Qualified with Opportunity' && updatedLead.ConvertedOpportunityId == null) {
updatedLead.Status.addError('You cannot use Qualified with Opportunity as a status value when not creating an opportunity');
}
}
}