We've been working with Attachment records on our custom objects, and we now need to migrate to Files (you know, that related list that shows up everywhere).
We have a lot of trigger logic on Attachment, and I need to get the exact same logic to work on Files (update fields of certain parent objects, prevent duplicates on some parent objects, prevent users from deleting other user's attachments/files...).
The problem is that the 3 relevant objects (ContentVersion
, ContentDocument
and ContentDocumentLink
) are illogical, no single object has all the data I need or is triggered in a sane manner. To try and understand I put some trace flages (System.debug()
) in the triggers, and I do not understand the results.
if (trigger.isBefore){
if (trigger.isUpdate){
for (ContentVersion cv : trigger.new){
System.debug('Content_Version_Trigger BEFORE UPDATE fired at: '+Datetime.now());
System.debug(cv);
}
}
else if (trigger.isInsert){
for (ContentVersion cv : trigger.new){
System.debug('Content_Version_Trigger BEFORE INSERT fired at: '+Datetime.now());
System.debug(cv);
}
}
else if (trigger.isDelete){
for (ContentVersion cv : trigger.old){
System.debug('Content_Version_Trigger BEFORE DELETE fired at: '+Datetime.now());
System.debug(cv);
}
}
}
else if (trigger.isAfter){
if (trigger.isUpdate){
for (ContentVersion cv : trigger.new){
System.debug('Content_Version_Trigger AFTER UPDATE fired at: '+Datetime.now());
System.debug(cv);
}
}
else if (trigger.isInsert){
for (ContentVersion cv : trigger.new){
System.debug('Content_Version_Trigger AFTER INSERT fired at: '+Datetime.now());
System.debug(cv);
}
}
else if (trigger.isDelete){
for (ContentVersion cv : trigger.old){
System.debug('Content_Version_Trigger AFTER DELETE fired at: '+Datetime.now());
System.debug(cv);
}
}
}
The same code (with different objects, obviously) appears in the ContentVersion
, ContentDocument
and ContentDocumentLink
triggers.
The relevant output is too large to post here.
Debug log from inserting one file
Debug log from updating the description of one file
It looks like the records are being created, modified and deleted in quick succession. Why?
What kind of effect will this have on my triggers? It seems as if I cannot reliably catch any single event, it's all or nothing. That of course, won't work, because I need different logic for different actions.
EDIT: I noticed that there was a bug in the trigger output. I fixed the trigger code and relinked the new output above. There are no deletes, but it looks like multiple ContentDocumentLink
s are created, and the ContentVersion
is updated accordingly.