0

I am saving a pdf and when using PageReference.getParameters().put('id', id), I get this error:

system.security.NoDataFoundException: Unable to retrieve object

This is my code:

AuraEnabled
public static string createDeclaracion(String name, String rut, String statement, string email){
    try{
        StatementOfFunds__c obj = new StatementOfFunds__c();
        obj.Name = name;
        obj.Rut__c = rut.replace('.', '');
        obj.RutDigitos__c = rut;
        obj.Statement__c = statement;
        obj.Email__c = email;
        insert obj;
        obj.File_Path__c = '/prepago/apex/PDFDeclaracionDeFondos?id=' + obj.Id;
        update obj;
        return Vass_FundsStatement.savePdf(name, obj.id);
    } catch (Exception e){
        return 'The following exception has occurred: ' + e.getMessage();
    }
}

public static string savePdf(string name, Id id){
    try{
        string pdfname = name + '/' + id;
        PageReference ref = Page.PDFDeclaracionDeFondos;
        ref.getParameters().put('id', id); //<-- here error
        ref.setRedirect(true);
        ContentVersion cv = new ContentVersion();
        cv.Title = pdfname;
        cv.PathOnClient = pdfname + '.pdf';
        cv.VersionData = ref.getContent();
        cv.Origin = 'H';
        insert cv;
        return Id;
    } catch (Exception e){
        delete [SELECT Id FROM StatementOfFunds__c Where Id = :id];
        return e.getMessage();
    }
}

This is my PDF

<apex:page standardController="StatementOfFunds__c" renderAs="pdf" applyBodyTag="false">

    <head>
        <style>
            body {
                font-family: 'Arial Unicode MS';
            }

            body hr {
                margin-bottom: 3%;
            }

            body div {
                margin-bottom: 6%;
            }

            .subtitle {
                text-decoration: underline;
            }
        </style>
    </head>

    <body>
        <center>
            <h1>Declaración de Origen de Fondos</h1>
        </center>
        <hr />
        <div>
            En cumplimiento al contrato de la tarjeta de Pago con Provisión de Fondos celebrado con el emisor Inversiones LP S.A., yo;
            <span class="subtitle">{!StatementOfFunds__c.Name}</span>, cédula de identidad N°
            <span class="subtitle">{!StatementOfFunds__c.RutDigitos__c}</span>, declaro que los fondos abonados en la cuenta de pago con provisión
            de Fondos, corresponden a:
        </div>
        <div class="subtitle">
            {!StatementOfFunds__c.Statement__c}
        </div>
        <div>
            La información declarada en este documento contiene el respaldo suficiente en caso de ser requerido por Inversiones L.P.
            S.A.
        </div>
        <div class="subtitle">
            A la fecha del
            <apex:outputText value="{0,date, dd/MM/yyyy HH:mm}">
                <apex:param value="{!StatementOfFunds__c.CreatedDate}" />
            </apex:outputText>Hrs.
        </div>
        <div>
            Nota:
            <br /> 1.-La solicitud de información se encuentra detallada en las condiciones de contrato de apertura de cuenta de
            provisión de fondos.
        </div>
        <div>
            2.-La no entrega de lo requerido podrá poner término a contrato de acuerdo a la letra j) de la cláusula séptima, del mismo.
        </div>
    </body>
</apex:page>

When I comment ref.getParameters().put('id', id), the pdf is saved smoothly but without the object data.

3
  • is the id a valid Id of a record the running user has visibility to?
    – cropredy
    Commented Mar 17, 2021 at 23:10
  • You can't get an error on the line that you say you're getting an error on. You can put in an Id or String freely in the parameter map, it won't fail until you get to the getContent call.
    – sfdcfox
    Commented Mar 17, 2021 at 23:16
  • and why did he fail on that line? Commented Mar 17, 2021 at 23:19

1 Answer 1

0

Well first of all, thanks for the help without the comments I would not have found the solution.

https://developer.salesforce.com/forums/?id=906F00000008yEHIAY

I am getting error Unable to retrieve object while using PageReference.getContentAsPdf() . I am getting this error only for partner community user

Indeed, the getContent() method could not find the user, because it had not finished creating the object yet. You must finish saving and then make a second call.

I remove the method that creates and saves the pdf

@AuraEnabled
public static string createDeclaracion(String name, String rut, String statement, string email){
    try{
        StatementOfFunds__c obj = new StatementOfFunds__c();
        obj.Name = name;
        obj.Rut__c = rut.replace('.', '');
        obj.RutDigitos__c = rut;
        obj.Statement__c = statement;
        obj.Email__c = email;
        insert obj;
        obj.File_Path__c = '/prepago/apex/PDFDeclaracionDeFondos?id=' + obj.Id;
        // Vass_FundsStatement.savePdf(name, obj.id); <-- remove
        update obj;
        return obj.id;
    } catch (Exception e){
        return 'The following exception has occurred: ' + e.getMessage();
    }
}

@AuraEnabled
public static string savePdf(Id id){
    try{
        PageReference ref = Page.PDFDeclaracionDeFondos;
        ref.getParameters().put('Id', id);
        ref.setRedirect(true);
        ContentVersion cv = new ContentVersion();
        cv.Title = id;
        cv.PathOnClient = id + '.pdf';
        cv.VersionData = ref.getContent();
        cv.Origin = 'H';
        insert cv;          
        return Id;
    } catch (Exception e){
        delete [SELECT Id
                FROM StatementOfFunds__c
                Where Id = :id];
        return e.getMessage();
    }
}

When the object is created, a second call is made to save the PDF.

 createStatement: function (component, event, helper) {
    var action = component.get("c.createDeclaracion");
    action.setParams({
        "name": component.get("v.Name"),
        "rut": component.get("v.Rut__c"),
        "statement": component.get("v.Statement__c"),
        "email": component.get("v.Email")
    });
    action.setCallback(this, function (response) {
        var state = response.getState();
        if (state === "SUCCESS") {
            //  I save the PDF after inserting the object
            var action = component.get("c.savePdf");
            action.setParams({
                "id": response.getReturnValue()
            });
            action.setCallback(this, function (response) {
                console.log(response.getReturnValue());
            });
            $A.enqueueAction(action);
        }
        else if (state === "ERROR") {
            helper.msjError(response);
        } 
    });
    $A.enqueueAction(action);
},

If there is a better way to do this I have no problem correcting it.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .