5

I try to create a simple LWC to display an iframe whose url should be store in a custom field of the object

So my html is

<template>
    <lightning-card title="URL" icon-name="custom:custom14">
        <iframe src={url} width="100%" style="border:0px" ></iframe>
    </lightning-card>
</template>

Then I added in the targetconfig of the js-meta file, in order to be able to have it as a parameter of my component

<property name="urlField" label="ObjectApiName.FieldApiname" type="String" default="" />

and my js file is

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

export default class UrlVisualizer extends LightningElement {
    @api recordId;
    @api urlField;

    @wire(getRecord, { recordId: '$recordId', optionalFields: ['$urlField']}) record;

    get url(){
        return (this.record.data ? getFieldValue(this.record.data, this.urlField) : '');
    }
}

I just add my component to the Account record page, telling the urlfield parameter to be Account.url__c But Nothing happen and the url is empty.

If I use a static reference to the field as below and use it instead of the parameter,

import URL_FIELD from '@salesforce/schema/Account.url__c';

all is fine, but I really want to reuse this component on different pages and would prefer it can be reusable.

Do you have any clue on how I can use parameters in the getrecord wire call?

Thanks

4

In lwc wire only simple/primitive fields are reactive. This means

'$recordId' is reactive but ['$urlField'] is not.

Thus you have to bind optionalFields to something you can @track.

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

export default class UrlVisualizer extends LightningElement {
    @api recordId;
    @api urlField  ;

    @track feildArray =[];

    connectedCallback(){
        this.feildArray = [this.urlField];
    }

    @wire(getRecord, { recordId: '$recordId', optionalFields: '$feildArray'}) record;

    get url(){

        return (this.record.data ?  getFieldValue(this.record.data ,this.urlField ):'');
    }



}
  • 1
    You rock, it works ! Thanks so much Pranay – Fred Gaume Apr 12 at 15:12
  • Same way is not working if tried with array of field names. Something like this: @api fields; @track fieldsArray = []; connectedCallback() { this.fieldsArray = [this.fields]; } This does not work. – Ashish Sharma Aug 7 at 13:37

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.