[SalesForce] How to get objectApiName in community on LWC

I'm trying to get the sObject Name on community record page.
Getting the recordId works! But getting the sObject name does not.. Can I get it automatically in community ?

followed this doc which says its possible :
https://developer.salesforce.com/docs/component-library/documentation/lwc/lwc.use_object_context

Thats my Lightning Web component markup:

XML :

`<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>47.0</apiVersion>
    <isExposed>true</isExposed>
    <masterLabel>My LWC</masterLabel>
    <description>Community Component</description>
     <targets>
        <target>lightningCommunity__Page</target>
        <target>lightningCommunity__Default</target>
    </targets>
    <targetConfigs>
    <targetConfig targets="lightningCommunity__Default">
        <property name="recordId" type="String" label="Record ID" default="{!recordId}" description="The value should be {!recordId}."/>
        <property name="objectApiName" type="String" label="Object Name" description="Bind the page's {!objectApiName} to the component variable" default="{!objectApiName}" />
    </targetConfig>
    </targetConfigs>
</LightningComponentBundle>`

JS

import { LightningElement, api} from 'lwc';
export default class MyComp extends LightningElement {
        @api recordId;
        @api objectApiName;

  connectedCallback() {
    console.log('recordId ' + this.recordId); // this works
    console.log('objectApiName ' + this.objectApiName); // this does not WORK ??
  }
}

Best Answer

From the discussion on this question it appears that there is a bug in the community builder that doesn't ensure the objectApiName value is made available, via the target property binding in the LWC's meta XML, unlike the recordId which seems to work.

The documentation does state, under Access Object Context in Communities, that a property must be used and includes the example:

<targetConfigs>
    <targetConfig targets="lightningCommunity__Default">
        <property
            name="objectApiName"
            type="String"
            label="Object Name"
            description="Automatically bind the page's object name to the component variable"
            default="{!objectApiName}" />
    </targetConfig>
</targetConfigs>

It is clear that this should work without explicitly stating the object's API name due to the default here (as per recordId).

The only caveat specified is:

NOTE This approach works only for components where the {!objectApiName} is in the route.

Either there's a bug or the specific usage here doesn't have the object API name as part of the URL.

Related Topic