Wednesday 3 April 2013


// ==================================================================================
//   Object: biuLead
//   Author: John Westenhaver
// Comments: Prevent duplicate Leads from being created or updated, based on a rule
//           that there can only be one open Lead for any given Email. Closed Leads
//           are ignored. Assumes that Email is required.
// ==================================================================================
//  Changes: 2012-08-01 Initial version.
// ==================================================================================

trigger biuLead on Lead (before insert, before update)
{
   // Get a list of all emails being inserted or updated.
   set emailSet = new set();

   map leadMap = new map();
   for (Lead l : system.trigger.new)
   {
      if ((l.Email != null) && 
          (system.trigger.isInsert || 
          (l.Email != system.trigger.oldMap.get(l.Id).Email)))
      {
         // Make sure a DIFFERENT new Lead isn't also a duplicate.
         if (emailSet.contains(l.Email))
         {
            l.Email.addError('Sorry, but more than one new Lead ' + 
               'has the same email address.');
         }
         else
         {
            emailSet.add(l.Email);
         }
      }
   }
   // Get all EXISTING open Leads that have the same email address.
   list leadList = 
      [SELECT Email FROM Lead WHERE Email IN :emailSet AND Status LIKE '%Open%'];
   if (leadList.size() > 0)
   {
      system.trigger.new[0].addError('Sorry, but there is already an ' +
         'open Lead with that Email address.');
   }
}
Categories: ,

0 comments:

Post a Comment

    Links