You need to sign in to do that
Don't have an account?

Updating a title of a ContentVersion record (a file) before insert
Hey guys, I'm trying to get through this. I have this code:
The problem is when I upload a file, it says this:
I think it means that the "a.ContentDocumentId" does not exist, so I can not use it. That is why cdaids is empty, hence the error.
The idea is that the trigger must get the ID of the related record of the file. Everything else is easy now. ContentVersion does not have a link to the related record, only ContentDocument has that (ParentId). Please give me an idea how to fix this?
trigger ContentVersionTitleUpdate on ContentVersion (before insert) { List<Id> saids = new List<Id>(); Set<Id> cdids = new Set<Id>(); for(ContentVersion a :Trigger.New) { if(a.ContentDocumentId != null){ cdids.add(a.ContentDocumentId); } ContentDocument[] cd = [Select Id, ParentId From ContentDocument where Id in :cdids]; if(cd[0] != null) { saids.add(cd[0].ParentId); } ServiceAppointment[] sa = [Select Id, FileTitle__c From ServiceAppointment where Id in :saids]; for (ContentVersion b :Trigger.New){ if(sa != null) { if(sa[0].FileTitle__c != 'DefaultValue') { b.Title = sa[0].FileTitle__c; } } } } }
The problem is when I upload a file, it says this:
Trigger.ContentVersionTitleUpdate: line 9, column 1 19:08:54.0 (12583025)|FATAL_ERROR|System.ListException: List index out of bounds: 0
I think it means that the "a.ContentDocumentId" does not exist, so I can not use it. That is why cdaids is empty, hence the error.
The idea is that the trigger must get the ID of the related record of the file. Everything else is easy now. ContentVersion does not have a link to the related record, only ContentDocument has that (ParentId). Please give me an idea how to fix this?
Here is the solution.
List<ContentDocument> cd = [Select Id, ParentId From ContentDocument where Id in :cdids];
if(!cd.isEmpty()) {
if(cd[0].ParentId != null) {
saids.add(cd[0].ParentId);
}
}
List<ServiceAppointment> sa = [Select Id, FileTitle__c From ServiceAppointment where Id in :saids];
for (ContentVersion b :Trigger.New){
if(!sa.isEmpty() ) {
if( sa[0].FileTitle__c != null && sa[0].FileTitle__c != 'DefaultValue') {
b.Title = sa[0].FileTitle__c;
}
}
}
All Answers
Here is the solution.
List<ContentDocument> cd = [Select Id, ParentId From ContentDocument where Id in :cdids];
if(!cd.isEmpty()) {
if(cd[0].ParentId != null) {
saids.add(cd[0].ParentId);
}
}
List<ServiceAppointment> sa = [Select Id, FileTitle__c From ServiceAppointment where Id in :saids];
for (ContentVersion b :Trigger.New){
if(!sa.isEmpty() ) {
if( sa[0].FileTitle__c != null && sa[0].FileTitle__c != 'DefaultValue') {
b.Title = sa[0].FileTitle__c;
}
}
}