2

I'm getting error in below method line no. 14

Error Message:

"System.CalloutException: You have uncommitted work pending. Please commit or rollback before calling out Error is in expression '{!step2}' in component in page documentxDoc: Class.DocumentController.step2: line 14, column 1"

Code Is:

 public PageReference step2() {
    String sTempType = null;
    List<Manual_Doc__c> lstMdoc = new List<Manual_Doc__c>();
    Manual_Doc__c oMdoc;
    for(Document tempDoc : lstSelectedDoc){
      oMdoc = new Manual_Doc__c();
      sTempType = tempDoc.sDocType;

      PageReference pagePdf = new PageReference('/apex/DocumentPdf');
      pagePdf.getParameters().put('id', oId);
      Blob pdfPageBlob;
      pdfPageBlob = pagePdf.getContentAsPDF();    
      Attachment attachmentPDF = new Attachment();
      attachmentPDF.Body = pdfPageBlob;
      attachmentPDF.ParentID = oId;
      attachmentPDF.Name = 'TerryTestAttach1.pdf';
      attachmentPDF.Description = 'TestDescription1';
      insert attachmentPDF;

      oMdoc.ObjectID__c = oId;
      oMdoc.Template__c = tempDoc.docId;
      oMdoc.Attachment_Id__c = attachmentPDF.Id;
      lstMdoc.add(oMdoc);
      oMdoc = null;
    }
    if(lstMdoc.size()>0){
      insert lstMdoc;
    }
    pageReference pg = new pageReference('/apex/DocumentMerge_2');
    pg.setRedirect(false);
    return pg;
  }
4

The cause is probably this Summer '15 - PageReference getContent() and getContentAsPDF() Methods Behave as Callouts. The change will be mandatory soon but perhaps someone has opted in early in an org.

The problem would appear when more than one document is selected: the insert attachmentPDF of the first document will count as a DML before the second getContentAsPDF call. A simple fix, providing the keeping the generated documents in memory does not exceed the 6M heap governor limit, is to add the attachmentPDF objects to a list and only do the insert after all the getContentAsPDF calls have been made.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.