0
trigger Attachtolead on Case (before insert) {
    list<lead> l =new list<lead>();
    list<case> clist =new list<case>();
    set<string> emailtext=new set<string>();
    list<case> cli=new list<case>();
    set<string> lid=new set<string>();
    for (case c : Trigger.new) {
        if(c.ContactID == null && c.Origin=='web')
            emailtext.add(c.SuppliedEmail);
        cli.add(c);
    }
    l=[select id,email,phone,country,fax from lead where email IN: emailtext];
    for(lead l1: l){
        lid.add(l1.id);
    }
    if(lid.size()>0){
        lead l2=[select id,email,phone,country,fax from lead where id IN:lid Limit 1];
        for (case c : cli) {
            c.Lead__c=l2.id; 
        } 
    }     
}

I want to connect case to lead checking with supplied email .but it is not working .can some one can help me regarding this ?

3
  • Nowhere in your trigger you are updating the Case or Lead. Just writting c.Lead__c=l2.id; will not update the Cases. Try writting " Update c; " after your FOR loop and see if it works or not.
    – Ruchi
    Commented Jan 13, 2016 at 6:37
  • I want to update case by attaching leading lead id to this field lead__c but it is not allow me to use dml statement Commented Jan 13, 2016 at 6:39
  • You have a bulkification problem... one moment.
    – sfdcfox
    Commented Jan 13, 2016 at 6:48

1 Answer 1

2

You should be using the Aggregate Query Update pattern, which would look like this:

trigger AssociateToLead on Case (before insert) {
    // Aggregate
    Map<String, Id> leadsByEmail = new Map<String, Id>();
    Case[] filtered = new Case[0];
    for(Case record: Trigger.new) {
         if(record.SuppliedEmail != null && record.ContactId == null && record.Origin == 'Web') {
              leadsByEmail.put(record.SuppliedEmail, null);
              filtered.add(record);
         }
    }
    // Query
    if(leadsByEmail.isEmpty()) {
        return;
    }
    for(Lead record: [SELECT Email FROM Lead WHERE Email IN :leadsByEmail.keySet() AND IsConverted = FALSE]) {
        leadsByEmail.put(record.Email, record.Id);
    }
    // Update
    for(Case record: filtered) {
        record.Lead__c = leadsByEmail.get(record.Email);
    }
}

As for why your code isn't working-- I couldn't even begin to guess. I do know that you'd eventually have problems with your code when you tried to load records manually, but your trigger should at least have worked assuming the SuppliedEmail matched at least one lead.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .