0

I am using record-edit-form and want to conditionally show fields on change of checkbox

HTML

<lightning-input-field field-name="Line_of_cover_Accident__c" onchange={toggleAccidentFields}> </lightning-input-field>
                    <template if:true={showAccidentFields}>
                        <lightning-input-field field-name="Annual_Premium_Accident__c" required> </lightning-input-field>
                        <lightning-input-field field-name="Number_of_Lives_Accident__c" required> </lightning-input-field>
                        <lightning-input-field field-name="Accident_Policy_Number_s__c" required> </lightning-input-field>
                    </template>

JS

export default class NetworkSearchSurvey extends LightningElement {
        @api recordId;
        @api networkSearchResponse;
        @api showSurvey = false;
        @api isLoaded = false;
    
        @api get showAccidentFields() {
            return this.networkSearchResponse.fields.Line_of_cover_Accident__c.value;
        }
    
        toggleAccidentFields() {
            this.showAccidentFields = !this.showAccidentFields;
        }
    }

I think the problem is that my getter runs when toggleAccidentFields() is triggered and just overrides anything done there but I'm not sure how to overcome this.

I tried just setting showAccidentFields = false; but that means that if the record is marked true and saved then the fields are hidden on the next load of the page.

1 Answer 1

1

You don't even have a setter, so this.showAccidentFields = !this.showAccidentFields would fail. Further, the @api property would make it read-only, even if you had a setter.

If you need to expose the field as a public property, use a backing variable with both a get and set:

_showAccidentFields;
@api get showAccidentFields() {
  return this._showAccidentFields;
}
set showAccidentFields(value) {
  this._showAccidentFields = value;
}
toggleAccidentFields() {
  this._showAccidentFields = !this._showAccidentFields;
}

If you don't need to expose showAccidentFields as a public property, you can:

    _networkSearchResponse;
    @api set networkSearchResponse(value) {
      this._networkSearchResponse = value;
      if(value) {
        this.showAccidentFields = value.fields.Line_of_cover_Accident__c.value;
      }
    }
    get networkSearchResponse() {
      return this._networkSearchResponse;
    }
    showAccidentFields = false;
    toggleAccidentFields() {
        this.showAccidentFields = !this.showAccidentFields;
    }

Note: I'd suggest using getFieldValue or getFieldDisplayValue as appropriate, instead of relying on a direct reference to the value.

1
  • thanks for this, worked perfectly! Getter/setter is not something I've used before so need to learn more about it.
    – Luke Bray
    Apr 28, 2022 at 9:52

You must log in to answer this question.

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