Use case
Once we will be working with generic component we may have to bind declared variables dynamically in code to get expected result .
Based on below example we can display account name for an particular 'accountId'
import { LightningElement, wire } from 'lwc';
import { getRecord, getFieldValue } from 'lightning/uiRecordApi';
import NAME_FIELD from '@salesforce/schema/Account.Name';
export default class Example extends LightningElement {
@wire(getRecord, { recordId: '0013xx065790ASZ', fields: [NAME_FIELD] })
account;
get name() {
return getFieldValue(this.account.data, NAME_FIELD);
}
}
Instead of importing the field definition in controller we can dynamically pass fields array within getrecord().
Lets have a look into the code.
Controller
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | /** * @File Name : dynamicbinding.js * @Description : * @Author : Swarup Satpti * @Group : * @Last Modified By : Swarup Satpati * @Last Modified On : 8/31/2020, 5:00:00 PM **/ import { LightningElement, api, wire, track } from 'lwc'; import { getFieldValue } from 'lightning/uiRecordApi'; import {getRecord} from 'lightning/uiRecordApi'; export default class Chevron extends LightningElement { @api objectName = 'Account'; @api fieldName = 'Name'; /*component with a recordId property is used on a Lightning record page, the page sets the property to the ID of the current record.*/ @api recordId='001W000000dls6ZIAQ'; @track record; @track error; @track fieldArray; @track fieldValue; connectedCallback(){ console.log("hi.."); this.fieldArray = [`${this.objectName}.${this.fieldName}`,`${this.objectName}.RecordTypeId`]; } /*Use this wire adapter to get a record’s data : Recordtype ID and value of status field pass through API */ @wire(getRecord, { recordId: '$recordId', fields:'$fieldArray'}) wiredAccount({ error, data }) { if (data) { this.record = data; console.log(JSON.stringify(data)); // this.fieldvalue=getFieldValue(data,`${this.objectName}.${this.fieldName}`); this.error = undefined; } else if (error) { console.log('error..'); this.error = error; this.record = undefined; } } get name() { return getFieldValue(this.record,`${this.objectName}.${this.fieldName}`); } } |
HTML Template
1 2 3 4 5 | <template> <div class="slds-m-around_medium"> <p>Account Name: {name}</p> </div> </template> |
Code Explanation:
within Js controller variables are dynamically bound using '$' sign as below.
this.fieldArray = [`${this.objectName}.${this.fieldName}`,`${this.objectName}.RecordTypeId`]
Finally Code will return the value of account name for given account ID .
Hope you got it useful....! cheers ..