Apex触发同步电子邮件同步帐户和联系人

时间:2015-12-11 16:49:24

标签: salesforce apex

我首先说我是Salesforce和Apex Triggers的完整菜鸟。

我们到目前为止所做的是在帐户记录中添加了自定义电子邮件字段。帐户记录通过外部集成(magento商店客户)自动创建。

我们还有来自不同外部集成(zendesk)自动创建的联系人记录。

我们想要发生的是,当创建新帐户时,如果存在使用相同电子邮件的记录,则所有帐户信息将被转移到联系人记录,如果联系人不存在,它将使用所有相同的帐户信息创建新联系人。

我认为只要创建/更新新帐户,就需要使用某种 upsert 触发器进行此操作?

编辑,这是我使用的当前触发器:

trigger UpsertTrigger on Account (after insert, after update) {

List<String> listAccountEmails = new List<Account>();
//capture all the account email updated
for( Account a : Trigger.new )
  {
     listAccountEmails.add(String.Valueof(a.Email));
  }

//Get all the related contacts match email address
List<Contact> listContacts = new List<Contact>();
listContacts = [SELECT Id, FirstName, LastName, Email FROM Contact WHERE Email in :listAccountEmails];

//Convert list Contacts into map with email as key
Map<String, Contact> mapContacts = Map<>(String, Contact);
for ( Contact c : listContacts)
   mapContacts.put(c.Email, c);

// Loop thru account emails and create contact record if email doesnot exist or //update contact if exist
 for (String e : listAccountEmails) {
    if (mapContacts.isContainsKey(e) == true) { 
//Map Account fields to Contact fields

              a.Last_Name__c = c.LastName,
              a.First_Name__c = c.FirstName,
              a.Magento_Customer_ID__c = c.Magento_Customer_ID__c,
              a.Sales_Rep__c = c.Sales_Rep__c,
              a.id = c.AccountId,
              a.Email__c = c.Email) 
      }
else
//Create New Contact

    Contact con = new Contact();

    con.LastName = a.Last_Name__c;
    con.FirstName = a.First_Name__c;
    con.Magento_Customer_ID__c = a.Magento_Customer_ID__c;
    con.Email = a.Email__c;
    con.Sales_Rep__c = a.Sales_Rep__c;
    con.AccountId = a.id;

    insert con; 
}

upsert Contacts;

1 个答案:

答案 0 :(得分:1)

我们没有单独的upsert类型的触发器。 Upsert执行两件事。 1.如果记录不存在,请插入。 2.更新记录(如果存在)。

对于此特定要求,您需要在帐户对象上编写触发器,如下所示。

trigger UpsertTrigger on Account (after insert, after update) {

List<String> listAccountEmails = new List<Account>();
//capture all the account email updated
for( Account a : Trigger.new )
  {
     listAccountEmails.add(String.Valueof(a.Email));
  }

//Get all the related contacts match email address
List<Contact> listContacts = new List<Contact>();
listContacts = [SELECT Id, FistName, LastName, Email, and other fields FROM Contact WHERE Email in :listAccountEmails];

//Convert list Contacts into map with email as key
Map<String, Contact> mapContacts = Map<>(String, Contact);
for ( Contact c : listContacts)
   mapContacts.put(c.Email, c);

// Loop thru account emails and create contact record if email doesnot exist or //update contact if exist
for (String e : listAccountEmails) {
    if (mapContacts.isContainsKey(e) == true) { 
                  Map the account fields to contact fields 
          }
    else
       Create contact records 
}

upsert Contacts;