【问题标题】:Prevent last contact from delete using trigger in salesforce使用 Salesforce 中的触发器防止删除最后一个联系人
【发布时间】:2016-06-14 11:32:25
【问题描述】:

我是 salesforce 的新手,我有一个需求,我需要建议如何处理这个需求

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

如何使用触发器实现这一点?

【问题讨论】:

    标签: triggers salesforce


    【解决方案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 中输入了这个,根本没有实际测试过代码,即使是缺少分号或大括号等语法错误。它在理论上应该有效,但可能有更好的方法。

    【讨论】:

      【解决方案2】:

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

      ContactCount__c = 0 &&  PRIORVALUE(ContactCount__c) > 0
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-03-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-02-14
        • 2016-09-19
        • 1970-01-01
        相关资源
        最近更新 更多