8

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

1 Answer 1

8

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 ):'');
    }



}
2
  • 2
    You rock, it works ! Thanks so much Pranay
    – Fred Gaume
    Commented Apr 12, 2019 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. Commented Aug 7, 2019 at 13:37

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .