Returning Contacts and Leads with Custom Wrapper Class

February 24th, 2009

Unfortunately alot of companies use Leads and Contacts interchangeably. Here is a small Apex class that performs a SOSL search across Contacts and Leads by email address. The method then wraps each Contact and Lead as a generic Person object and returns them to the caller as a List.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
 
public class PersonService {
 
    public class Person {
 
        String id;
        String firstName;
        String lastName;
        String company;
        String email;
        String phone;
        String sObjectType;
 
    }
 
    public static List searchByEmail(String email) {
 
        // list of Person objects to return
        List people = new List();
 
        // issue the sosl search
        List<list> searchResults = [FIND :email IN EMAIL FIELDS RETURNING
            Contact (Id, Account.Name, Email, Phone, FirstName, LastName),
            Lead (Id, Company, FirstName, LastName, Email, Phone)];
 
        // cast the results by sObjec type
        List contacts = ((List)searchResults[0]);
        List leads = ((List)searchResults[1]);
 
        // a each contact found as a Person
        for (Integer i=0;i<contacts.size();i++) {
            Person p = new Person();
            p.id = contacts[i].Id;
            p.firstName = contacts[i].FirstName;
            p.lastName = contacts[i].LastName;
            p.company = contacts[i].Account.Name;
            p.email = contacts[i].Email;
            p.phone = contacts[i].Phone;
            p.sObjectType = 'Contact';
            people.add(p);
        }
 
        // a each lead found as a Person
        for (Integer i=0;i<leads.size();i++) {
            Person p = new Person();
            p.id = leads[i].Id;
            p.firstName = leads[i].FirstName;
            p.lastName = leads[i].LastName;
            p.company = leads[i].Company;
            p.email = leads[i].Email;
            p.phone = leads[i].Phone;
            p.sObjectType = 'Lead';
            people.add(p);
        }
 
        System.debug('Returning people: '+people);
 
        return people;
 
    }
}
  • Share/Bookmark

Related posts:

  1. Using PHP to call an Apex Web Service
  2. Programmatically Creating Sharing Rules with Apex
  3. Apex Search with Checkbox Results
  4. Using List Custom Settings in Salesforce.com
  5. Use an Inline Visualforce Page with Standard Page Layouts

Categories: Apex, Salesforce

Leave a comment

Leave a comment

Feed

http://blog.jeffdouglas.com / Returning Contacts and Leads with Custom Wrapper Class