Mapping recordIds to Object Names - Offline edition
Lightning in Communities is "Same Same but different". When you want to build neutral components, you need to know what object you are dealing with
ObjectApiName, ObjectName and recordId
In Lightning Aura components one can use force:hasSObjectName
to get access to an attribute sObjectName
. In Lightning Web components one uses @api objectApiName
. Except neither of those work in Communities.
The workaround is to look at the recordId
and use DescribeSObjectResult.getKeyPrefix
to map a record to the object name. There's a comprehensive list by David and my version as JSON object.
However, depending on your org, that list might vary. So I created a small component that lists out the objects in your current org. Enjoy:
ObjectIdSpy.cls
public without sharing class ObjectIdSpy {
@AuraEnabled(cacheable=true)
public static Map<String,String> getObjectIdMappings(){
Map<String,String> result = new Map<String,String>();
Map<String, Schema.SObjectType> gd = Schema.getGlobalDescribe();
for(String key : gd.keySet()) {
Schema.SObjectType ot = gd.get(key);
String curPrefix = ot.getDescribe().getKeyPrefix();
String curName = ot.getDescribe().getName();
// Fair warning: will omit objects that share the prefix
result.put(curPrefix, curName);
}
return result;
}
}
objectIdSpy.html
<template>
<lightning-card title="Object Spy">
<pre>
{idList}
</code></pre>
</lightning-card>
</template>
objectIdSpy.js
import { LightningElement, track, wire } from "lwc";
import idSpy from "@salesforce/apex/ObjectIdSpy.getObjectIdMappings";
export default class ObjectIdSpy extends LightningElement {
@track idList;
@wire(idSpy)
spiedUpon({ error, data }) {
if (data) {
this.idList = JSON.stringify(data, null, 2);
} else if (error) {
this.idList = JSON.stringify(error, null, 2);
}
}
}
objectIdSpy.js-meta.xml
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="ObjectIdSpy">
<apiVersion>45.0</apiVersion>
<isExposed>true</isExposed>
<masterLabel>Object Id Spy</masterLabel>
<description>Generates a JSON object of Id and object names</description>
<targets>
<target>lightning__RecordPage</target>
<target>lightning__AppPage</target>
<target>lightning__HomePage</target>
</targets>
</LightningComponentBundle>
As usual YMMV!
Posted by Stephan H Wissel on 20 March 2019 | Comments (0) | categories: Salesforce Singapore