0

I have been following this guide to create a Web Component that gets a records information, however I am having trouble getting this to work with custom object... Is there extra steps you need to take to get this to work with custom objects?

For example, here is what I have in my own code:

import { LightningElement, api, wire} from 'lwc';
import { getRecord, getFieldValue } from 'lightning/uiRecordApi';

const STUDENT_FIELDS = [
    'Student__c.Name',
    'Student__c.username__c'
]

export default class StudentCourseRelationship extends LightningElement {
    @api recordId;

    // STUDENT
    @wire(getRecord, { recordId: '$recordId', STUDENT_FIELDS}) student;

    get studentName() {
        // OPTION 1
        return getFieldValue(this.student.data, STUDENT_FIELDS[0]);
        // OPTION 2
        return this.student.data.fields.Name.value
    }

    get studentUsername() {
        // OPTION 1
        return getFieldValue(this.student.data, STUDENT_FIELDS[1]);
        // OPTION 2
        return this.student.data.fields.username__c.value
    }

}

As you can see, in my get methods I have explained 2 options. In Option 1, nothing errors but nothing is displayed in the view where I attempt to display studentName and studentUsername. And in Option 2, I get the error: [undefined is not an object (evaluating 'this.student.data.fields')]

1

You have missed to specify the fields attribute in @wire declaration. The @wire decorator should be declared as below (note fields: STUDENT_FIELDS):

@wire(getRecord, { recordId: '$recordId', fields: STUDENT_FIELDS}) student;

From the documentation:

The @wire decorator tells getRecord to get the values of the specified fields on the record with the specified $recordId.

The fields attribute being used in the JS functions contains the response from the Record data (excerpt below). And that, in your current declaration, you haven't mapped this attribute to the fields that you are retrieving.

The field data for this record, matching the requested layout and mode.

  • Even after adding the fields declaration, I still get the error [undefined is not an object (evaluating 'this.student.data.fields')] – BlondeSwan Feb 20 at 19:44
  • Try refreshing your component, it could be a caching issue. – Jayant Das Feb 20 at 19:45
  • Returning getFieldValue(this.student.data, STUDENT_FIELDS[0]); works fine. – BlondeSwan Feb 20 at 19:46

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.