计算帐户的活跃联系人总数
我在联系人上创建了一个复选框来表示其状态(active__c),并为帐户对象创建了另一个自定义字段,该字段表示活动联系人的总数(activeContact__c)。
下面的代码工作正常,但是当我将任何帐户的活跃联系人总数设置为零时,它仍然为 1。
您能解释一下我在这里做错了什么吗?谢谢。
trigger CountActiveContacts on Contact (after insert , after update) {
switch on Trigger.operationType {
when AFTER_INSERT, AFTER_UPDATE {
List<Account> accountList = new List<Account>();
Set<Id> accIds = new Set<Id>();
for(Contact c : Trigger.new){
accIds.add(c.AccountId);
}
AggregateResult[] groupedResult = [select accountid accID, count(id) totalCountOfActiveContacts from contact where active__c = true and AccountId =: accIds group by accountid ];
for(AggregateResult result: groupedResult){
accountList.add(new Account(id= (id)result.get('accID'), activeContact__c= (Integer) (result.get('totalCountOfActiveContacts'))));
}
update accountList;
}
}
}
I have created a checkbox on contacts to represent it's status (active__c ) and another custom field for account object, which represent total number of active contacts (activeContact__c).
Below code is working fine but when I am making the total active contacts to zero for any account, it still come as 1.
Could you please explain what I am doing wrong here? Thanks.
trigger CountActiveContacts on Contact (after insert , after update) {
switch on Trigger.operationType {
when AFTER_INSERT, AFTER_UPDATE {
List<Account> accountList = new List<Account>();
Set<Id> accIds = new Set<Id>();
for(Contact c : Trigger.new){
accIds.add(c.AccountId);
}
AggregateResult[] groupedResult = [select accountid accID, count(id) totalCountOfActiveContacts from contact where active__c = true and AccountId =: accIds group by accountid ];
for(AggregateResult result: groupedResult){
accountList.add(new Account(id= (id)result.get('accID'), activeContact__c= (Integer) (result.get('totalCountOfActiveContacts'))));
}
update accountList;
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当最后一个联系人未被选中时,您的查询开始返回 0 行,
因此不再需要循环。
尝试将帐户制作为地图并将计数器初始化为零。你甚至不需要这套套装
When last contact got unticked your query starts to return 0 rows
so there's nothing to loop over anymore.
Try making the Accounts as a Map and initialise the counter to zero. And you won't need the Set even