I need to achieve multiple download on list view of Invoice object
.
Requirement: Invoice Object has Notes and Attachments Related list. If Notes and Attachment is not null for Invoice Record then it should download the InvoicePDF(vfp) if attachment is null for Invoice Record then it should download InvoiceWithoutAttachmentPDF(vfp)
.
I tried something but I can achieve the correct download on single selection of Record on List view. If i try to download Multiple records its downloading the last one record only.
for example:
If I click on two invoices called,
- Invc-00000001 (with Attachments) it should download the InvoicePDF
- Invc-00000002 (with Attachments) it should download the InvoicePDF
It is only downloading the second Invoice with the name Invc-00000002. I think the problem is with the looping only. I can't able to find.
How to overcome this?
Code snippet is more helpful thanks!!
Here is my code
global class DownloadInvoice
{
// Receive Attachments info from Attachment ParentId
private static String API_STATUS_NORMAL = '200';
webService static string getAttachmentByParentId(string sfdcId)
{
List<id> ids = new List<id>();
if(string.isempty(sfdcId))
{
return DownloadInvoiceResponse.errorJson('Parameter sfdcId is required.');
}
string[] idsArray = sfdcId.split(',');
for(integer i=0; i<idsArray.size();i++)
{
ids.add(idsArray[i]);
}
List<Invoice__c> invList = New List<Invoice__c>();
invList = [Select id, name, Print_Invoice__c,Account__r.name from Invoice where ID IN: ids];
List<Attachment> attInsert = new List<Attachment>();
if(invList.size() > 0)
{
for(Invoice__c invc : invList)
{
Blob body;
Attachment[] attachments = [SELECT ParentId FROM Attachment where ParentId IN:ids];
for (Attachment a : attachments)
{
attchmentParentIds.add(a.ParentId);
}
Integer WithAttachCount = [SELECT count() FROM Attachment where ParentId IN:ids AND id !=null]
for(integer i = 1; i<= invList.size(); i++)
{
if(WithAttachCount > 0 && attchmentParentIds.get(0) == invc.Id)
{
PageReference pdf = new PageReference('/apex/InvoicePDF?id='+invc.id);
body = pdf.getContentAsPDF();
}else if(WithAttachCount <= 0)
{
PageReference pdff = new PageReference('/apex/InvoiceIfAttachIsNull?id='+invc.id);
body = pdff.getContentAsPDF();
}
}
attach.Body = body;
attach.name= invc.name +'_Invoice_'+ Datetime.Now() +'.PDF';
attach.IsPrivate = false;
attach.ParentId = invc.id;
attach.contentType = 'application/pdf';
attInsert.add(attach);
}
}
Insert attInsert;
}