I like using Chatter Files for Attachments because they are prettier and searchable. The downside is that, when you add one to an Opporutunity, you don't see it as an Attachment on the Account like an old-skool Attachment would.
So I am working on a trigger where, if a user posts a Chatter File to an Opportunity, it also links it up to the Account. Sample code is below. I am successfully checking for it being a Chatter File (ContentPost) and only running when linked to an Opportunity, but the trigger runs whether I am adding a new file and also if I am associating an existing file to an Opportunity.
Any ideas how to determine whether the ContentPost is using a new Chatter File or an Existing one?
for (FeedItem f: fis){
String parentIdString = String.valueOf(f.parentId);
if (parentIdString.startsWith(Opportunity.sObjectType.getDescribe().getKeyPrefix()) && f.type == 'ContentPost'){
Opportunity o = [select id, accountId from Opportunity where id = :f.ParentId limit 1][0];
if(o.AccountId != null){
FeedItem newFI = new FeedItem();
newFI.Type = 'ContentPost';
newFI.RelatedRecordId = f.RelatedRecordId;
newFI.ParentId = o.AccountId;
newFI.title = f.title;
insert newFI;
}
}
}
NOTE: I am already aware of the issue with querying and DML in the loop. I will fix that later. I am mostly concerned with getting the scenario correctly handled.
Thanks, StackExchange!