Monday, 6 September 2021

How to get parent record Id from URL and pass to LWC component ?

Use Case - Lets assume we have custom child object named "TRW__c" to parent Lead. you need to override New button of  TRW object. Unfortunately we cant override New button with LWC, then aura is suggested approach. 
Some other approach is use intermediate Visualfoce page then use lighting-out features.

I'm going to explain how to use LWC component wrapped inside aura.

Challenge - We will not get Lead record Id easily unlike we get if component is being used as global action. {!v.recordId}

Here is the workaround to get parent record id and pass to your LWC. This will be useful when your standard button/action is overridden.

LWC component name - createBAFormLWC
<template>
     <template if:true={loading}>
        <lightning-spinner></lightning-spinner>
    </template>
    <div> BA form Id - {leadId} </div>
</template>

Java script
import { LightningElement,api } from 'lwc'; export default class CreateBAFormLWC extends LightningElement { @api leadId; }

Aura component - createBAFormAura
<aura:component 
implements="lightning:actionOverride,flexipage:availableForRecordHome,
force:hasRecordId" access="global" >
    <aura:handler name="init" value="this" action="{!c.doInit}"/>
    <aura:attribute name="parentRecordId" type="String" />
    <p>Id-{!v.parentRecordId}</p>
     <c:createBAFormLWC leadId="{!v.parentRecordId}"/>
</aura:component>

Controller
({ doInit : function(component, event, helper) { var value = helper.getParameterByName(component , event, 'inContextOfRef'); console.log('value--'+value); var context = JSON.parse(window.atob(value)); console.log('context.attributes.recordId--'+context.attributes.recordId); component.set("v.parentRecordId", context.attributes.recordId); } })

Helper
({ getParameterByName: function(component, event, name) { name = name.replace(/[\[\]]/g, "\\$&"); var url = window.location.href; var regex = new RegExp("[?&]" + name + "(=1\.([^&#]*)|&|#|$)"); var results = regex.exec(url); if (!results) return null; if (!results[2]) return ''; return decodeURIComponent(results[2].replace(/\+/g, " ")); } })


No comments: