I had such issue. I created method that save attachent to my Opportunity.
public PageReference attachInvoicePDF() {
/* Get the page definition */
PageReference pdfPage = Page.Invoice_PDF_V2;
pdfPage.getParameters().put('id', oppId);
/* generate the pdf blob */
Blob pdfBlob;
if(Test.isRunningTest()) {
pdfBlob = blob.valueOf('Unit.Test');
} else {
pdfBlob = pdfPage.getContentAsPDF();
}
Attachment attach;
Attachment[] a;
//Get attachment
a = [SELECT Id, Name, Body, ContentType, ParentId From Attachment WHERE parentId = :oppId];
/* create the attachment for opportunity*/
if (a.size() == 0) {
attach = new Attachment(parentId = oppId, name=opportun.Invoice_Number__c + '.pdf', body = pdfBlob);
insert attach;
} else {
attach = a[0];
}
//Insert ContentVersion
ContentVersion cVersion = new ContentVersion();
cVersion.ContentLocation = 'S';
cVersion.PathOnClient = attach.Name;
cVersion.Origin = 'C';
//cVersion.OwnerId = attach.OwnerId;
cVersion.Title = attach.Name;
cVersion.VersionData = pdfBlob;
Insert cVersion;
//After saved the Content Verison, get the ContentDocumentId
Id conDocument = [SELECT ContentDocumentId FROM ContentVersion WHERE Id =:cVersion.Id].ContentDocumentId;
//Insert ContentDocumentLink
ContentDocumentLink cDocLink = new ContentDocumentLink();
cDocLink.ContentDocumentId = conDocument;
cDocLink.LinkedEntityId = attach.ParentId;
cDocLink.ShareType = 'V';
cDocLink.Visibility = 'AllUsers';
Insert cDocLink;
return pdfPage;
}
I wrote test for this method and debug it. T\I see the problem here:
a = [SELECT Id, Name, Body, ContentType, ParentId From Attachment WHERE parentId = :oppId];
I call two times my method in test. First time my method should use if block.
if (a.size() == 0) {
attach = new Attachment(parentId = oppId, name=opportun.Invoice_Number__c + '.pdf', body = pdfBlob);
insert attach;
} else {
attach = a[0];
}
And second call should use else block but it use if block again. Can you help me why my second call don't see inserted Attachment after first call?
Also I have two VF pages: Page.Invoice_PDF and Page.Invoice_PDF_V2
Because when I use one page, it creates infinite loop. Maybe the problem is here?