0

On the Opportunity object, I have a Quick action that generates a pdf file using a ContentDocument (the else block) and creates a new version of the ContentDocument (the if block). I need the following condition: if the file already exists in the system with this name, create a new version of it.

I think we need to use soql query, extract name from ContentDocument, if there is such name, that is query != null, create its new version with if block, else create pdf file with such name.

I couldn't get soql query into if logic, so I created custom object on which I created field, trying to extract title from ContentVersion where Title Opportunity.Invoice_Number__c. (The file name is stored in Invoice_Number__c&Opportunity)

My code creates a new version if there's already a file with this name, BUT if there's no file with this name, it won't create me a ContentDocument giving me an error

message: "List has no rows for assignment to SObject"

stackTrace: "Class.controllerTest.savePDF: line 11, column 1"

Line: invoice.ConName__c=[select Title from ContentVersion where Title=: opps.Invoice_Number__c].id;

What am I missing?

1 Answer 1

0

SOQL always returns a list, it may be empty or have a value.

[SELECT ContentDocumentId FROM ContentVersion WHERE Title =: fileName] This will return a List<ContentVersion>

But if you write it like this:

Id contentDocumentId = [SELECT ContentDocumentId FROM ContentVersion WHERE Title =: fileName].ContentDocumentId;

This will first make SOQL try to fetch a record and from that record fetch ContentDocumentId. So if you dont have a record in DB it will fail with List has no rows for assignment to SObject, which means SOQL tried to fetch the row and assign it to ContentVersion, but was unable to do so.

To avoid this:

Make sure to let SOQL always return a List.

List<ContentVersion> contentVersions = [SELECT ContentDocumentId FROM ContentVersion WHERE Title =: fileName];
if(!contentVersions.isEmpty()){
    Id contentDocumentId = contentVersions.get(0).ContentDocumentId;
    // Logic goes here
}
1
  • thank you, that's work.
    – user111471
    Commented Feb 17, 2022 at 9:26

You must log in to answer this question.