I have been trying to get a trigger to fire when a new attachment is inserted (After insert), the ParentId is Event for that attachment, and the Event is related to an Account.
So, if anyone inserts an attachment on an Event and that event is related to an Account the following needs to happen:
- A Chatter FeedItem needs to be inserted for the Event Owner followers.
- A Chatter FeedItem needs to be inserted for the related Account followers for that event.
- List item
Note: On the code expose here I'm trying only the account followers.
I know this can be very tricky and I'm trying to at least get it fired, not so such luck so far. The Trigger is on an After Trigger context variable.
Here is the code:
trigger AttachmentTrigger on Attachment (after insert) {
List<FeedItem> feedList = new List<FeedItem>();
Set<Id> accIds = new Set<Id>();
Set<Id> ownIds = new Set<Id>();
Set<Id> eveIds = new Set<Id>();
for(Attachment a: trigger.new)
{
if(a.ParentId.getSObjectType() == Event.SObjectType)
{
eveIds.add(a.ParentId);
}
}
System.debug('Event size ' +eveIds.size());
if(!eveIds.isEmpty()){
Map<Id, Event> evenList = new Map<Id, Event>([SELECT OwnerId, Account.Id FROM Event WHERE Id IN :eveIds AND Account.Id != null]);
for(Event e: evenList.values()){
accIds.add(e.Account.Id);
ownIds.add(e.OwnerId);
}
}
System.debug('Account from event size ' +accIds.size());
System.debug('Owner from event size ' +ownIds.size());
List<EntitySubscription> entityListAcct = [SELECT id, ParentId, SubscriberId FROM EntitySubscription WHERE ParentId IN :accIds];
List<EntitySubscription> entityListOwn = [SELECT id, ParentId, SubscriberId FROM EntitySubscription WHERE ParentId IN :ownIds];
System.debug('This is the entityListAcct size: ' + entityListAcct.size());
System.debug('This is the entityListOwn size: ' +entityListOwn.size());
for(EntitySubscription entityAcct: entityListAcct)
{
if(!entityListAcct.isEmpty() && entityListAcct.size()>0)
{
FeedItem accountFeedItem= new FeedItem(
ParentId = entityAcct.SubscriberId,
Body ='This is a message from hell!!');
feedList.add(accountFeedItem);
}
}
System.debug('This is the feedList size: '+feedList.size());
if(!feedList.isEmpty() && feedList.size()>0){
insert feedList;
}
}
Any tips on how to get this trigger to fire or why is not firing?? Any help would be much appreciated. Thanks.