function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Caroline PooleCaroline Poole 

Making my LWC Aware of Its Record Context

Hi All!

The LWC I've created lives on the Opportunity record page - and I want the LWC to pull all of the related records from an object titled, 'Junction - Opportunity/Competitor'. Right now, I am only able to hard code the recordid that the component pulls from. 

I am trying to get my LWC (a lightning-datatable) to pull in the recordid automatically so that the component shows information relevant to the record you're viewing.



relatedlist_competitor.cls

public with sharing class relatedlist_competitor {
    @AuraEnabled(cacheable = true)
public static List<Junction_Competitor_Opportunity__c> fetchCompetitor (String Opportunityid){
       return [SELECT Id,Competitor_Name_for_Flow__c,Bullet_1__c,Bullet_2__c,Opportunity__c FROM Junction_Competitor_Opportunity__c WHERE Opportunity__c = :Opportunityid];
    }
}


relatedlist_competitor.html
<template>

        <!--lightning datatable-->
         <lightning-datatable 
               key-field="id"
               data={parameters.data}
               onrowaction={handleRowAction}
               row-number-offset={rowOffset}
               hide-checkbox-column="true"
               columns={columns}></lightning-datatable>
                  
           <!-- Detail view modal start -->
         <template if:true={bShowModal}>
          <section role="dialog" tabindex="-1"
                   aria-labelledby="modal-heading-01"
                   aria-modal="true"
                   aria-describedby="modal-content-id-1"
                  class="slds-modal slds-fade-in-open">
             <div class="slds-modal__container">
                <!-- modal header start -->
                <header class="slds-modal__header">
                   <button class="slds-button slds-button_icon slds-modal__close slds-button_icon-inverse" title="Close" onclick={closeModal}>
                      <lightning-icon icon-name="utility:close" alternative-text="close" variant="inverse" size="small" ></lightning-icon>
                   </button>
                   <h2 id="modal-heading-01" class="slds-text-heading_medium slds-hyphenate">Record Detail</h2>
                </header>
                <!-- modal body start -->
                <div class="slds-modal__content slds-p-around_medium" id="modal-content-id-1">
                  <dl class="slds-list_horizontal slds-wrap">
                      <dt class="slds-item_label" title="Name">Competitor Name</dt>
                      <dd class="slds-item_detail">{record.Competitor_Name_for_Flow__c}</dd>
                  </dl>
                </div>
                <div class="slds-modal__content slds-p-around_medium" id="modal-content-id-2">
                     <dl class="slds-list_horizontal slds-wrap">
                         <dt class="slds-item_label" title="Name">Bullet 1</dt>
                         <dd class="slds-item_detail">{record.Bullet_1__c}</dd>
                     </dl>
                   </div>
                   <div class="slds-modal__content slds-p-around_medium" id="modal-content-id-3">
                        <dl class="slds-list_horizontal slds-wrap">
                            <dt class="slds-item_label" title="Name">Bullet 2</dt>
                            <dd class="slds-item_detail">{record.Bullet_2__c}</dd>
                        </dl>
                      </div>
                <!-- modal footer start-->
                <footer class="slds-modal__footer">
                     <lightning-button variant="brand"
                     label="Close"
                     title="Close"
                     onclick={closeModal}
                     ></lightning-button>
                </footer>
             </div>
          </section>
          <div class="slds-backdrop slds-backdrop_open"></div>
       </template>
       <!-- Detail view modal end -->
  
      </template>

relatedlist_competitor.js
import {
    LightningElement,
    wire,
    api,
    track,
} from 'lwc';
 
//import method from the Apex Class
import fetchCompetitor from '@salesforce/apex/relatedlist_competitor.fetchCompetitor';
 
// Declaring the columns in the datatable
const columns = [{
        label: '',
        type: 'button-icon',
        initialWidth: 75,
        typeAttributes: {
            iconName: 'utility:picklist_type',
            title: 'Preview',
            variant: 'border-filled',
            alternativeText: 'View'
        }
    },
    {
        label: 'Competitor',
        fieldName: 'Competitor_Name_for_Flow__c'
    },
];
 
// declare class to expose the component
export default class DataTableComponent extends LightningElement {
    @track columns = columns;
    @track record = {};
    @track rowOffset = 0;
    @track data = {};
    @track bShowModal = false;
    @api recordid;
    @wire(fetchCompetitor, {Opportunityid:"00629000008UIbbAAG"}) parameters;
 
    // Row Action event to show the details of the record
    handleRowAction(event) {
        const row = event.detail.row;
        this.record = row;
        this.bShowModal = true; // display modal window
    }
 
    // to close modal window set 'bShowModal' tarck value as false
    closeModal() {
        this.bShowModal = false;
    }
}

relatedlist_competitor.js-meta.xml
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="dataTableComponent">
    <apiVersion>45.0</apiVersion>
    <isExposed>true</isExposed>
    <!-- With following targets make component available for lightning app page, record page and home page in salesforce --><targets>
        <target>lightning__RecordPage</target>
    </targets>
</LightningComponentBundle>

 
Khan AnasKhan Anas (Salesforce Developers) 
Hi Caroline,

Greetings to you!

If a component is used on a Lightning record page, you can pass the component the ID of the current record. In the component’s JavaScript class, use the @api decorator to create a public recordId property.
 
// testClass.js
import { LightningElement, api } from 'lwc';
export default class TestClass extends LightningElement {
    @api recordId;
}

When your component is invoked in a record context in Lightning Experience or in the mobile app, recordId is set to the 18-character ID of the record.

Please refer to the below links which might help you further with the above requirement.

https://developer.salesforce.com/docs/component-library/documentation/lwc/lwc.use_record_context

https://www.santanuatonline.com/how-to-get-current-user-id-record-id-and-object-api-name-in-lwc/

https://rajvakati.com/2018/12/29/get-record-id-into-lightning-web-components/

https://medium.com/@tempflip/wiring-up-lightning-web-components-26b1c00d247d

I hope it helps you.

Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future. It will help to keep this community clean.

Thanks and Regards,
Khan Anas
Caroline PooleCaroline Poole

Hey Khan!

Thanks so much for these articles! Unfortunately, it doesn't seem like this is doing the trick. I have used the @api decorator to create a public recordid property (see .js in my original message), but when I pull the component on to the record page in app builder, the component brings up no data.

Thoughts?!

Thanks again,

Caroline

MTBRiderMTBRider
Hi Caroline.   Did you find the issue with this problem?   I am having the same problem...added the @api recordId property per the developer guide but it is not getting populated with the record Id.  Thanks
MTBRiderMTBRider
I found the issue that I was having with this.  I have a child component that was within the a parent component and I was trying to get the record Id within the child component.  Once I moved the retrieval of the record Id to the parent component I was good.  Just posting this here for others that may come across this post.
Caroline PooleCaroline Poole

This is great!! Do you mind posting your code so I can use it as a reference for mine?

 

MTBRiderMTBRider
Here are some snippets of my code.  My solution is not a pure LWC solution because I needed some functionality that is not currently available with LWC.  Specificaly I needed to display some pre-formatted HTML so I needed the <aura:unescapedHtml> component.  So I used an Aura component as the parent component and LWC as a child component.  

Here is the parent aura component that gets the record Id and sObject name (by implementing force:hasRecordId and force:hasSObjectName) and then passes it to the JS for the LWC via the recId and objName attributes on <c:scheduleGenerator>
<aura:component implements="force:hasRecordId,flexipage:availableForRecordHome,force:hasSObjectName">
    <aura:attribute name="showSchedule" type="boolean" default="false"/>
    <aura:attribute name="scheduleHtml" type="String" />
    <aura:attribute name="modalTitle" type="String" default="Schedule"/>
               
    <div >
        <c:scheduleGenerator onscheduleready="{!c.displaySchedule}" aura:id="lwcGenerator" recId="{!v.recordId}" objName="{!v.sObjectName}"></c:scheduleGenerator>
    </div>

    <aura:if isTrue="{!v.showSchedule}">
        <section role="dialog" tabindex="-1" class="slds-modal slds-fade-in-open slds-modal_medium" aria-labelledby="modal-heading-01" aria-modal="true" aria-describedby="modal-content-id-1">
            <div class="slds-modal__container">
            <header class="slds-modal__header">
                <h2 id="modal-heading-01" class="slds-modal__title slds-hyphenate">{!v.modalTitle}</h2>
            </header>
            <div class="slds-modal__content slds-p-around_medium" id="modal-content-id-1">
                <div style="width:100%; text-align: center;">
                    <aura:unescapedHtml value="{!v.scheduleHtml}"></aura:unescapedHtml>
                </div>
            </div>
                <footer class="slds-modal__footer">
                    <lightning:button label="Cancel" onclick="{!c.closeScheduleDlg}"/>
                    <lightning:button variant="brand" label="Save"/>
                </footer>
            </div>
        </section>
            <div class="slds-backdrop slds-backdrop_open"></div>
    </aura:if>
</aura:component>

Then in the JS for the LWC the record Id and object name is placed in the global recId and objName vars:
 
import { LightningElement, wire, track, api } from 'lwc';

export default class scheduleGenerator extends LightningElement {
    @api recId;
    @api objName;

...

Hope this helps!