I have a custom object named News where i have custom text field called Image ids. I want to store Ids of all the images i would attach as attachment. I want to store the ids seperated by commas.
And i want to delete the Ids from text field if and attachment is deleted.
Here is my code;
trigger PopulateIdValueinProduct on Attachment (after insert, after update, after delete, after undelete) {
Map<Id,List<Attachment>> parent = new Map<Id,List<Attachment>>();
set<id> attids = new set<id>();
if(Trigger.new<>null){
for(Attachment c:Trigger.new){
FT_News__c l;
if(c.ParentId != null)
attids.add(c.parentid);
}
}else if(Trigger.old != null){
for(Attachment c:Trigger.old){
if(c.ParentId<>null)
attids.add(Trigger.oldMap.get(c.id).parentid);
}
}
if(attids.size()>0){
try{
List<Attachment> a = new List<Attachment>();
Map<id,FT_News__c> newsmap = new Map<id,FT_News__c>([select id,FCC_ImageIds__c from FT_News__c where id IN: attids]);
a = [select id,parentid from Attachment where parentid IN:attids];
for(Attachment at: a){
List<Attachment> llist = new List<Attachment>();
if(parent.get(at.parentid) == null){
llist = new List<Attachment>();
llist.add(at);
parent.put(at.parentid,llist);
}else if(parent.get(at.parentid) != null){
llist = new List<Attachment>();
llist = parent.get(at.parentid);
llist.add(at);
parent.put(at.parentid,llist);
}
}
for(Id i: attids){
if(newsmap.get(i) != null && parent.get(i) != null){
for(Attachment eachNews: parent.get(i)){
newsmap.get(i).FCC_ImageIds__c += String.ValueOf(eachNews.Id) +',';
}
}else if(testmap.get(i) != null && parent.get(i) == null){
newsmap.get(i).FCC_ImageIds__c = '';
}
}
update newsmap.values();
System.Debug(testmap.values());
}catch(Exception e){}
}
}
thanks in advance!