function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
rlupurlupu 

About how to create items related to a new lead, but prevent the creation of the lead itself

The Salesforce implementation I'm trying to work with contains:
- lead_source_code__c as a custom text field of the Lead object
- Lead_Source_Code__c as a custom object that contains a custom lookup(Lead) field called lead__c


Whenever a new lead becomes candidate for insertion,
- I have to check the database for unconverted leads that have the same identification key (name+company+email) as the new lead
- If there are such leads, I have to pick up the most recent one and to check if the lead_source_code of the incoming lead has
  already been part of the collection of lead_source_codes of the chosen existing lead.
- If it hasn't, then the new lead_source_code must be added to the collection of the existing lead and the incoming lead creation
  must be prevented.

Below is part of the code that I'm trying to use for this purpose.

trigger AddLeadSourceToCollection on Lead (before insert)
{
    for (Lead ld:System.Trigger.new)
    {
       //find the most recent unconverted lead that has the same identification key  as the new lead
            Lead[] unconv_lds_coll=[select id,createddate from lead where isdeleted=false and isconverted=false and firstname=:ld.firstname and lastname=:ld.lastname and company=:ld.company and email=:ld.email order by createddate asc];
            datetime most_rec;
            ID ld_id;
            for (Lead unconv_ld:unconv_lds_coll)
            {
              most_rec=unconv_ld.createddate;
              ld_id =unconv_ld.id;
            }
       //Find out whether the value of the Lead_Source_Code field of the new lead
       //has already existed
       //in the collection of Lead_Source_Codes of the unconverted lead you previously found.
       //If it hasn't existed, it must be added and the new lead shouldn't be created any more.
            integer ldsrc_exists;
            ldsrc_exists=[select count() from Lead_Source_Code__c where isdeleted=false and lead__c=:ld_id and name=:ld.lead_source_code__c];
            if (ldsrc_exists==0)
            {
              Lead_Source_Code__c ldsrc=new Lead_Source_Code__c(lead__c=ld_id, name=ld.lead_source_code__c);
              insert ldsrc;
            }
       ld.addError('The new lead was not inserted.');   
    }
}


It seems natural to me that the addError method, which prevents the creation of the new lead, rolls back the part that was supposed
to add the new lead_source_code to the collection of the existing lead. However, I don't know any other way to prevent the
creation of the new lead and allow the addition of the new lead_source_code.

If any of you can help, please do it.
Thank you