You need to sign in to do that
Don't have an account?
vijay kumar k
show the number of attachments in account custom field
hi please help me to write test class for below trigger or post the test class
trigger countattachments on attachment(after insert, after delete,after undelete) {
Map<Id, List<attachment>> Amap = new Map<Id, List<attachment>>();
Set<Id> AcctIds = new Set<Id>();
List<Account> AcctList = new List<Account>();
List<attachment> alist = new List<attachment>();
if(trigger.isInsert||trigger.isundelete ) {
for(attachment a : trigger.New) {
if(String.isNotBlank(a.parentid)){
AcctIds.add(a.parentId);
}
}
}
if(trigger.isDelete) {
for(attachment a1 : trigger.Old) {
AcctIds.add(a1.parentId);
}
}
if(AcctIds.size() > 0){
alist = [SELECT Id, parentId FROM attachment WHERE parentId IN : AcctIds];
for(attachment a2 : alist) {
if(!Amap.containsKey(a2.parentId)){
Amap.put(a2.parentid, new List<attachment>());
}
Amap.get(a2.parentid).add(a2);
}
AcctList = [SELECT Number_of_attachments__c FROM Account WHERE Id IN : AcctIds];
for(Account Acc : AcctList) {
List<attachment> atList = new List<attachment>();
atList = Amap.get(Acc.Id);
Acc.Number_of_attachments__c = atList.size();
}
update AcctList;
}
}
thank you
vijay
trigger countattachments on attachment(after insert, after delete,after undelete) {
Map<Id, List<attachment>> Amap = new Map<Id, List<attachment>>();
Set<Id> AcctIds = new Set<Id>();
List<Account> AcctList = new List<Account>();
List<attachment> alist = new List<attachment>();
if(trigger.isInsert||trigger.isundelete ) {
for(attachment a : trigger.New) {
if(String.isNotBlank(a.parentid)){
AcctIds.add(a.parentId);
}
}
}
if(trigger.isDelete) {
for(attachment a1 : trigger.Old) {
AcctIds.add(a1.parentId);
}
}
if(AcctIds.size() > 0){
alist = [SELECT Id, parentId FROM attachment WHERE parentId IN : AcctIds];
for(attachment a2 : alist) {
if(!Amap.containsKey(a2.parentId)){
Amap.put(a2.parentid, new List<attachment>());
}
Amap.get(a2.parentid).add(a2);
}
AcctList = [SELECT Number_of_attachments__c FROM Account WHERE Id IN : AcctIds];
for(Account Acc : AcctList) {
List<attachment> atList = new List<attachment>();
atList = Amap.get(Acc.Id);
Acc.Number_of_attachments__c = atList.size();
}
update AcctList;
}
}
thank you
vijay
But my trigger shows error at delete the last attachment , so please help me.