• kevin05
  • NEWBIE
  • 0 Points
  • Member since 2018

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 1
    Questions
  • 0
    Replies

I have a class which looks for if there is a PDF already attached to a custom object record as well as a date field being less than TODAY. How do I have this class attach an additional file if another parameter is met? For instance if there is already a PDF attached to the record called "Letter.pdf." I would like an additional letter to be attached because the record has been edited to SecondLetter__c = TRUE. Thanks for your help.

 

global class pdfBatch implements Database.Batchable<sObject> {
    
    String query;
    String filename = 'Letter.pdf';
    
    global pdfBatch() {
        query = 'SELECT Id FROM Application__c ';
        query += 'WHERE Publish_Date_Time__c < TODAY';
    }
    
    global Database.QueryLocator start(Database.BatchableContext BC) {
        return Database.getQueryLocator(query);
    }

    global void execute(Database.BatchableContext BC, List<Application__c> scope) {
        String[] appIDs = new LIST<String>();
        for(Application__c app : scope){
            appIDs.add(app.id);
        }
        SET<String> appIDsWithPDFs = new SET<String>();
        for(Attachment atchmnt : [
            SELECT ParentId 
            FROM Attachment 
            WHERE name =:filename
            AND ParentId IN :appIDs
            LIMIT 5000
        ]){
            appIDsWithPDFs.add(atchmnt.ParentId);
        }
        Attachment[] attachments = new LIST<Attachment>();
        for(Application__c app : scope)
        {
            if(appIDsWithPDFs.contains(app.id)) continue;
            PageReference pdf = Page.Letter_PDFer;
            // add parent id to the parameters for standardcontroller
            pdf.getParameters().put('id',app.id);

            // the contents of the attachment from the pdf
            Blob body;

            try {

            // returns the output of the page as a PDF
            body = pdf.getContent();

            // need to pass unit test -- current bug  
            } catch (VisualforceException e) {
            body = Blob.valueOf('An error occurred.');
            }

            Attachment attachment = new Attachment();
            attachment.Body = body;
            attachment.Name = String.valueOf(filename);
            attachment.ParentId = app.id;
            attachments.add(attachment);
        }
        if (attachments.size()>0)
            insert attachments;     
    }
    
    global void finish(Database.BatchableContext BC) {
        
    }
    
}

  • September 25, 2018
  • Like
  • 0