I want to automatically change the name of a file as soon as it is created. To keep things simple, let's say I want to add "test-" before the file name.
I think this has to be done via a trigger, but if you have any other solution, please feel free to offer it.
There are several Salesforce objects that have to do with files: ContentDocument, ContentVersion and some others. By experimentation, I think that ContentDocument is the one that is most suitable for a trigger in my case.
So this is my experimental trigger, yes, if has not been bulkified, so please don't comment on that (although I know some people will do it anyway):
trigger ContentDocumentTrigger on ContentDocument(after insert) {
List<Id> cdIds = new List<Id>();
for (ContentDocument cd : Trigger.new) {
System.debug('cd.Id = ' + cd.Id);
System.debug('cd.Title = ' + cd.Title);
cdIds.add(cd.Id);
}
System.debug('cdIds.size = ' + cdIds.size());
List<ContentDocument> cdsToUpdate = new List<ContentDocument>();
for (Id cdId : cdIds) {
System.debug('cdId = ' + cdId);
ContentDocument cd = [SELECT Id, Title FROM ContentDocument WHERE Id = :cdId][0];
System.debug('cd.Id = ' + cd.Id);
System.debug('cd.Title = ' + cd.Title);
cd.Title = 'test-' + cd.Title;
cdsToUpdate.add(cd);
}
update cdsToUpdate;
}
It is not possible to update the title in a before insert trigger, which would be the simplest solution. That will give you an error that title is not writeable.
So it must be an after insert trigger and since Trigger.new objects can not be updated directly (it results in a "object is read-only" error), I think it must be done in the way that I do it here.
So what goes wrong here? The Ids that I collect in the List turn out to be useless. The SELECT query results in zero returned records, even though I see in the debug log that the list contains seemingly valid Ids.
Am I making a mistake in my trigger? Is this even a good way of accomplishing what I want or do I have to do it in a completely different way?
ContentVersion