-2

Whenever the Account on Contact record changes, the contact should be converted back to a Lead. I have mapping fields from contact to lead. Is this possible ? How to achieve this ?

I'm trying to do it by writing a trigger:

trigger insertLead on Contact (before update,before delete) {
    Set<Id> aId = new Set<Id>();
    Lead myLead = new Lead();

    for (Contact opp : Trigger.new ) {
        aId.add(opp.AccountId);
        List<Account> acc = [select Name from Account where Id in:aId];
        List<Contact> con = [select LastName,FirstName from Contact where accountId = :aId];

        for(Account a: acc){
            myLead.Company = a.Name;
        }

        for(Contact c: con)
        {
            myLead.LastName = c.LastName;
            myLead.FirstName = c.FirstName;
        }
    insert myLead;
}

This is the error:

Error:Apex trigger insertLead caused an unexpected exception, contact your administrator: insertLead: execution of BeforeUpdate caused by: System.DmlException: Insert failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Required fields are missing: [Company]: [Company]: Trigger.insertLead: line 15, column 1

slugster
  • 49,403
  • 14
  • 95
  • 145

1 Answers1

0

I have checked and your trigger is working fine for Update on Contact. To work for delete add below condition.

trigger insertLead on Contact (before update,before delete) {
    Set<Id> aId = new Set<Id>();
    Lead myLead = new Lead();
    if (Trigger.isUpdate)
    {
    for (Contact opp : Trigger.new ) {
        aId.add(opp.AccountId);
        List<Account> acc = [select Name from Account where Id in:aId];
        List<Contact> con = [select LastName,FirstName from Contact where AccountId = :aId];

        for(Account a: acc){
            myLead.Company = a.Name;
        }

        for(Contact c: con)
        {
            myLead.LastName = c.LastName;
            myLead.FirstName = c.FirstName;
        }
        insert myLead;
    }
    else if(if (Trigger.isDelete)
    {
        for (Contact opp : Trigger.old ) {
            aId.add(opp.AccountId);
            List<Account> acc = [select Name from Account where Id in:aId];
            List<Contact> con = [select LastName,FirstName from Contact where AccountId = :aId];

            for(Account a: acc){
                myLead.Company = a.Name;
            }

            for(Contact c: con)
            {
                myLead.LastName = c.LastName;
                myLead.FirstName = c.FirstName;
            }
            insert myLead;
        }
    }
}

Regards,

Naveen

SSE

http://www.autorabit.com

naveen
  • 159
  • 2
  • 8