0

Can I use uiRecordApi getRecord to get dynamically record?

I am developing a custom lightning web component which can be placed on different record pages (Account, Contact, and Custom objects).

I am trying to substitute the object name value dynamically but this doesn't work.

When I try to use this code

@api objectApiName;

FIELDS = [
    this.objectApiName + '.Name'
];
@wire(getRecord, { recordId: '$recordId', fields: '$FIELDS'}) //, fields: `$objectApiName.Name`
wiredGetRecord({ error, data }) {
    // eslint-disable-next-line no-debugger
    debugger;
    if (data) {
        this.record = data;
        this.error = undefined;
        this.title = 'New Agreement for ' + this.record.fields.Name.value;
    } else if (error) {
        this.error = error;
        this.record = undefined;
    }
}
record;

I see two different errors

1)

aura_proddebug.js:5163 Error: [LWC error]: Can’t read the value of property `objectApiName` from the constructor because the owner component hasn’t set the value yet. Instead, use the constructor to set a default value for the property.
"The "fields" query string parameter contained object api names that do not correspond to the api names of any of the requested record ids. The requested object api names were: [undefined], while the requested records had object types: [Contract]"

When I use another code

objectName = '$objectApiName';
FIELDS = [
    this.objectName + '.Name'
];

I see another error

"The "fields" query string parameter contained object api names that do not correspond to the api names of any of the requested record ids. The requested object api names were: [$objectApiName], while the requested records had object types: [Contract]"

Is this possible to get this working using Lightning Data Service?

1 Answer 1

1

Looks like this is not possible to achieve with Lightning Data Service.

A custom Apex method and imperative Apex should be used to get this done.

@AuraEnabled
public static SObject getRecord(Id recordId, String objectApiName) {
    return Database.query('SELECT Name FROM ' + objectApiName ' + WHERE Id = \'' + recordId + '\'');
}

Import the method in LWC

import getRecordName from '@salesforce/apex/Controller.getRecord'

Call this method in connectedCallback

connectedCallback() {
    getRecordName({ recordId: this.recordId, objectApiName: this.objectApiName})
    .then(result => {
        // eslint-disable-next-line no-debugger
        debugger;
        console.log(result);
    })
    .catch(error => {
        this.displayError(error);
    })
    .finally(() => {
    });

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.