使用salesforce中的触发器阻止上次联系被删除

时间:2016-06-14 11:32:25

标签: triggers salesforce

我是salesforce的新手,我需要建议如何处理此要求

我有4个与一个帐户相关的联系人,当有人删除联系人时,他应该无法删除与该帐户相关的最后一个联系人。例如:在帐户A1中我有4个联系人,有人从中删除了3个联系人帐户然后应该删除,之后只有1个与该帐户相关的联系人,并且有人试图删除最后一个联系人,而不是删除它。

如何使用触发器实现此目的?

2 个答案:

答案 0 :(得分:1)

在触发器中,针对与该帐户相关的所有联系人运行查询。如果您尝试在此触发器中删除所有这些,请不要允许它。我不知道你想如何处理同时删除多个联系人的人,但是假设你只是禁止整个删除,用户必须用较少的联系人重试。如果你想提出一些删除除1个联系人以外的所有逻辑,那取决于你。 类似的东西:

Trigger OnContactDelete on Contact (before delete) {
   Set<ID> accountIds = new Set<ID>(); //all accounts that contacts are being deleted from
   for (Contact contact : Trigger.old) {
       accountIds.add(contact.AccountId);
   }

   List<Contact> contacts = [SELECT Id, AccountId FROM Contact WHERE AccountId IN :accountIds]; //get all of the contacts for all of the affected accounts

   Map<ID, Set<ID>> deleteMap = new Map<ID, Set<ID>>(); //map an account ID to a set of contact IDs being deleted
   Map<ID, Set<ID>> foundMap = new Map<ID, Set<ID>>(); //map an account ID to a set of contact IDs that were found by the query

   for (Contact deleteContact : Trigger.old) {
     Set<ID> idSet = deleteMap.get(deleteContact.AccountId);
     if (idSet == null) {
       idSet = new Set<ID>();
     }

     idSet.add(deleteContact.Id);
     deleteMap.put(deleteContact.AccountId, idSet);
   }

   for (Contact foundContact : contacts) {
     Set<ID> idSet = foundMap.get(foundContact.AccountId);
     if (idSet == null) {
       idSet = new Set<ID>();
     }

     idSet.add(foundContact.Id);
     foundMap.put(foundContact.AccountId, idSet);
   }

   for (ID accountId : accountIds) { //go through each affected account
     Set<ID> deleteIds = deleteMap.get(accountId);
     Set<ID> foundIds = foundMap.get(accountId);

     if (deleteIds != null && foundIds != null && deleteIds.containsAll(foundIds)) {
       for (Contact contact : Trigger.old) {
         if (deleteIds.contains(contact.Id)) { //this is one of the contacts being deleted
           contact.addError('This contact is potentially the last contact for its account and cannot be deleted');
         }
       }
     }
   }
 }

注意,我只是在SO中输入它并且根本没有测试过代码,即使是缺少分号或大括号等语法错误。它应该在理论上有效,但可能有更好的方法。

答案 1 :(得分:0)

您无需触发即可解决此问题。您可以在Account上创建一个汇总汇总字段,用于计算联系人记录(ContactCount__c)并在帐户验证规则中评估此计数,如下所示:

ContactCount__c = 0 &&  PRIORVALUE(ContactCount__c) > 0