VisualForce Page data not displayed after uploading to "Notes and Attachments"

As the below given, there is a quick action in Account page, which enters Contact details and on saving, it redirects to the Contact page where a pdf is attached in the 'Notes and Attachments' of Contact page(pdf is generate while it redirects to Contact Page after saving). The problem is no data is displayed in the attached PDF. But the recordId of the new Contact record has been generated. Then why the data of that record cannot be fetched by query? Please Help.

HTML:

<template>
<lightning-quick-action-panel title="Enter Contact Details">
    <h1>Enter Contact Name</h1>
    <p aria-required="true">Salutation</p>
    <lightning-input placeholder="Mr./Mrs./Ms." onchange={handleSalName} value={SalName}></lightning-input>
    <p aria-required="true">First Name</p>
    <lightning-input placeholder="Enter your first name" onchange={handleFName} value={FName}></lightning-input>
    <p aria-required="true">Last Name</p>
    <lightning-input placeholder="Enter your last name" onchange={handleLName} value={LName}></lightning-input>
    <p aria-required="true">E-Mail</p>
    <lightning-input placeholder="[email protected]" onchange={handleEmail} value={Email}></lightning-input>
    <lightning-button label="Save" onclick={handleSave}></lightning-button>
</lightning-quick-action-panel>

JS:

import { LightningElement, api, track } from 'lwc';
import createContact from '@salesforce/apex/ContactController.createContact';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import { NavigationMixin } from 'lightning/navigation';

export default class DataAccToContact extends NavigationMixin(LightningElement) {

@track SalName = '';
@track FName = '';
@track LName = '';
@track Email = '';

_recordId;

@api
get recordId() {
    return this._recordId;
}

set recordId(value) {
    this._recordId = value;
    console.log('record Id is : ', this._recordId);
}

handleSalName(event) {
    this.SalName = event.target.value;
    console.log('Salutation is : ', this.SalName);
}

handleFName(event) {
    this.FName = event.target.value;
    console.log('First Name is :', this.FName);
}

handleLName(event) {
    this.LName = event.target.value;
    console.log('Last Name is :', this.LName);
}

handleEmail(event) {
    this.Email = event.target.value;
    console.log('Email is :', this.Email);
}

handleSave() {
    createContact({ salutation: this.SalName, firstName: this.FName, lastName: this.LName, email: this.Email })
        .then(result => {
            this.showToast('Success', 'Contact created successfully', 'success');
            this[NavigationMixin.Navigate]({
                type: 'standard__recordPage',
                attributes: {
                    recordId: result,
                    objectApiName: 'Contact',
                    actionName: 'view'
                }
            });
        })
        .catch(error => {
            this.showToast('Error', error.body.message, 'error');
        });
}

showToast(title, message, variant) {
    const event = new ShowToastEvent({
        title: title,
        message: message,
        variant: variant
    });
    this.dispatchEvent(event);
}
}

Apex:

public class Contactcontroller {
@AuraEnabled
public static String createContact(String salutation, String firstName, String lastName, String email) {
    // Create the contact
    Contact newContact = new Contact(
        Salutation = salutation,
        FirstName = firstName,
        LastName = lastName,
        Email = email
    );
    insert newContact;

    System.debug('Id'+newContact.Id);
   
    //store quote pdf to notes and attachments of quote page
    PageReference pageRef = Page.ContactPDF;
    System.debug('ID '+newContact.Id);
    Contact con = [select Id, Name from Contact where Id=:newContact.Id LIMIT 1];
    System.debug('Con '+con);
    pageRef.getParameters().put('id', newContact.Id);

    Blob body;

    try {
        body = pageRef.getContent();
        System.debug('Blob content '+body);
    } catch (Exception e) {
        body = Blob.valueOf(e.getMessage());
        System.debug('Blob content in error '+body);
    }

    String cName = 'Contact_PDF';
    Date tday = Date.today();
    String pdfName = cName+'_'+tday.Month()+'/'+tday.Day()+'/'+tday.Year();

    ContentVersion conVer = new ContentVersion();
    conVer.ContentLocation = 'S'; // TO USE S specify this document IS IN Salesforce, TO USE E FOR external files
    conVer.PathOnClient = pdfName + '.pdf'; 
    conVer.Title = pdfName; 
    conVer.VersionData = body;
    INSERT conVer;  

    Id conDoc = [SELECT ContentDocumentId FROM ContentVersion WHERE Id = :conVer.Id].ContentDocumentId;

    ContentDocumentLink conDocLink = new ContentDocumentLink();
    conDocLink.LinkedEntityId = newContact.Id;
    conDocLink.ContentDocumentId = conDoc; 
    conDocLink.shareType = 'V';
    INSERT conDocLink;


    return newContact.Id;
}
}

VF Page:

<apex:page renderAs="pdf" controller="ContactPDFController">
<apex:pageBlock title="Contact Details">
    <apex:pageBlockSection columns="1">
        <apex:outputField value="{!contact.Salutation}" />
        <apex:outputField value="{!contact.FirstName}" />
        <apex:outputField value="{!contact.LastName}" />
        <apex:outputField value="{!contact.Email}" />
    </apex:pageBlockSection>
</apex:pageBlock>
</apex:page>

VF Page Controller:

public class ContactPDFController {
public Contact contact { get; set; }

public ContactPDFController() {
    if (ApexPages.currentPage().getParameters().containsKey('id')) {
        String contactId = ApexPages.currentPage().getParameters().get('id');
        contact = [SELECT Salutation, FirstName, LastName, Email FROM Contact WHERE Id = :contactId];
    }
}
}

I was expecting that the visualforce page will render as PDF with all the data, and thus show in the Attachments as a pdf file.

Upvotes: 0

Views: 18

Answers (0)

Related Questions