+ Start a Discussion
Oscar Fernando De la CruzOscar Fernando De la Cruz 

How to use id from Record Contact?

Hi everyone, I'm  new on LWC . and  I'm doing  this example to generate a PDF https://santanuboral.blogspot.com/2020/10/lwc-generate-pdf.html
everything works fine  but now Im trying to save the PDF to  the  correspondet contact depending on the ID,  any idea of how I can do that?   this is my code as we can see Im hard coding the id 

 
public with sharing class DisplayRichTextHelper {
    @AuraEnabled
public static Attachment generatePDF(String txtValue){

        Pagereference pg = Page.renderAsPDF;
        pg.getParameters().put('displayText', txtValue);

        Contact con = new Contact(Id='0035f000008RNWCAA4');

        Attachment objAttachment = new Attachment();
        objAttachment.Name = 'J2S.pdf';
        objAttachment.ParentId = con.Id;
        objAttachment.Body = pg.getContentaspdf();
        objAttachment.IsPrivate = false;
        insert objAttachment;
        return objAttachment;
    }
}
 

And i want to change for some like this:
 ApexPages.currentPage().getParameters().get('id');
Best Answer chosen by Oscar Fernando De la Cruz
Maharajan CMaharajan C
Hi Oscar,

I hope you are using this LWC Component in Contact Record Page.

Please add the below changes in your code.

Apex Class:
 
public with sharing class DisplayRichTextHelper {
    
    @AuraEnabled
    public static Attachment generatePDF(String txtValue, String contactId){
        Pagereference pg = Page.renderAsPDF;
        pg.getParameters().put('displayText', txtValue);
        Attachment objAttachment = new Attachment();
        objAttachment.Name = 'J2S.pdf';
        objAttachment.ParentId = contactId;
        objAttachment.Body = pg.getContentaspdf();   
        objAttachment.IsPrivate = false;
        insert objAttachment;
        return objAttachment;
    }
    
}

LWC JS:

1. Add the api in import...

2. Declare the @api recordId;

3. Chnage in generatePDF({txtValue: editor.value , contactId : this.recordId })
import { LightningElement, api } from 'lwc';
import generatePDF from '@salesforce/apex/DisplayRichTextHelper.generatePDF';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';


export default class LWCPDFGenerator extends LightningElement {

    @api recordId;

    allowedFormats =  ['font', 'size', 'bold', 'italic', 'underline', 'strike',
    'list', 'indent', 'align', 'link', 'image', 'clean', 'table', 'header', 'color',
    'background','code','code-block'];

    //this method will display initial text
    get myVal() {
        return '**Generate PDF using LWC Component 2 **';
    }

    attachment; //this will hold attachment reference

    /*This method extracts the html from input rich text 
        and pass this to apex class' method via implcit call
    */
    saveAsPdf(){
        const editor = this.template.querySelector('lightning-input-rich-text');
        //implicit calling apex method
        generatePDF({txtValue: editor.value , contactId : this.recordId })
        .then((result)=>{
            this.attachment = result;
                console.log('attachment id=' + this.attachment.Id);
                //show success message
                this.dispatchEvent(
                    new ShowToastEvent({
                        title: 'Success',
                        message: 'PDF generated successfully with Id:' + this.attachment.Id,
                        variant: 'success',
                    }),
                );
        })
        .catch(error=>{
            //show error message
            this.dispatchEvent(
                new ShowToastEvent({
                    title: 'Error creating Attachment record',
                    message: error.body.message,
                    variant: 'error',
                }),
            );
        })
    }
    
    /*
        This method updates the selected text with defined format
    */
    handleClick() {
        const editor  = this.template.querySelector('lightning-input-rich-text');
        const textToInsert = 'Journey to Salesforce'
        editor.setRangeText(textToInsert, undefined, undefined, 'select')
        editor.setFormat({bold: true, size:24, color: 'green', align: 'center',});
    }
}

In XML File:
 
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>52.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__RecordPage</target>
    </targets>
</LightningComponentBundle>

Thanks,
Maharajan.C

All Answers

Maharajan CMaharajan C
Hi Oscar,

I hope you are using this LWC Component in Contact Record Page.

Please add the below changes in your code.

Apex Class:
 
public with sharing class DisplayRichTextHelper {
    
    @AuraEnabled
    public static Attachment generatePDF(String txtValue, String contactId){
        Pagereference pg = Page.renderAsPDF;
        pg.getParameters().put('displayText', txtValue);
        Attachment objAttachment = new Attachment();
        objAttachment.Name = 'J2S.pdf';
        objAttachment.ParentId = contactId;
        objAttachment.Body = pg.getContentaspdf();   
        objAttachment.IsPrivate = false;
        insert objAttachment;
        return objAttachment;
    }
    
}

LWC JS:

1. Add the api in import...

2. Declare the @api recordId;

3. Chnage in generatePDF({txtValue: editor.value , contactId : this.recordId })
import { LightningElement, api } from 'lwc';
import generatePDF from '@salesforce/apex/DisplayRichTextHelper.generatePDF';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';


export default class LWCPDFGenerator extends LightningElement {

    @api recordId;

    allowedFormats =  ['font', 'size', 'bold', 'italic', 'underline', 'strike',
    'list', 'indent', 'align', 'link', 'image', 'clean', 'table', 'header', 'color',
    'background','code','code-block'];

    //this method will display initial text
    get myVal() {
        return '**Generate PDF using LWC Component 2 **';
    }

    attachment; //this will hold attachment reference

    /*This method extracts the html from input rich text 
        and pass this to apex class' method via implcit call
    */
    saveAsPdf(){
        const editor = this.template.querySelector('lightning-input-rich-text');
        //implicit calling apex method
        generatePDF({txtValue: editor.value , contactId : this.recordId })
        .then((result)=>{
            this.attachment = result;
                console.log('attachment id=' + this.attachment.Id);
                //show success message
                this.dispatchEvent(
                    new ShowToastEvent({
                        title: 'Success',
                        message: 'PDF generated successfully with Id:' + this.attachment.Id,
                        variant: 'success',
                    }),
                );
        })
        .catch(error=>{
            //show error message
            this.dispatchEvent(
                new ShowToastEvent({
                    title: 'Error creating Attachment record',
                    message: error.body.message,
                    variant: 'error',
                }),
            );
        })
    }
    
    /*
        This method updates the selected text with defined format
    */
    handleClick() {
        const editor  = this.template.querySelector('lightning-input-rich-text');
        const textToInsert = 'Journey to Salesforce'
        editor.setRangeText(textToInsert, undefined, undefined, 'select')
        editor.setFormat({bold: true, size:24, color: 'green', align: 'center',});
    }
}

In XML File:
 
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>52.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__RecordPage</target>
    </targets>
</LightningComponentBundle>

Thanks,
Maharajan.C
This was selected as the best answer
Oscar Fernando De la CruzOscar Fernando De la Cruz
Hi Maharajan.C , Thank you so much for answer me