0

I am creating LWC which will have both <lightning-record-edit-form> and <lightning-record-view-form> elements. I am toggling between these elements to edit and display the record. My code is as below

HTML:

<template>
  <template if:false={showFields}>
    <lightning-record-edit-form record-id={recordId} object-api-name={ObjectName} onsubmit={handleSubmit}>
      <lightning-button type="submit" label="Update Record"></lightning-button>
      <!--
      Few fields to update with custom styling
      -->
    </lightning-record-edit-form>
  </template>
  <template if:true={showFields}>
    <lightning-record-view-form record-id={recordId} object-api-name={ObjectName} onsubmit={handleSubmit}>
       <lightning-button onclick={toggleViewEdit} label="Edit Record"></lightning-button>
       <!--
       Few fields to display with custom styling
       -->
    </lightning-record-view-form>
  </template>
</template>

JS:

import {lightningElement, api} from 'lwc';

export default class myLWC extends lightningElement{
  @api recordId;
  showFields = true;
  
  toggleViewEdit(){
    if(!this.showFields){
      this.showFields = true;
    }else{
      this.showFields = false;
    }
  }
  
  handleSubmit(event){
    event.preventDefault();
    const fields = event.detail.fields;
    this.template.querySelector('lightning-record-edit-form').submit(fields);
    this.toggleViewEdit();//This should only execute after successful submit action
  }
}

I only want to switch from edit-form to view-form when all the validation errors are successfully resolved. I tried reportValidity(), but still not getting what I need it to be.

3
  • Welcome to sfse! You can try removing toggleViewEdit() from handle submit and move it to a new function that can be called from handleSuccess of edit form
    – Raul
    Commented Oct 10, 2022 at 15:49
  • Thanks Raul, How to call that function only after submit is successful? Commented Oct 10, 2022 at 15:58
  • Similar to onsubmit there is onsuccess in record edit form
    – Raul
    Commented Oct 10, 2022 at 16:06

1 Answer 1

0

try below approach

    <template>
  <template if:false={showFields}>
    <lightning-record-edit-form record-id={recordId} object-api-name={ObjectName} onsubmit={handleSubmit} onsuccess={handleSuccess}>
      <lightning-button type="submit" label="Update Record"></lightning-button>
      <!--
      
</template>

 

js

handleSuccess = (event) => {
    this.toggleViewEdit();
}
1
  • Thanks @sdandamud1 :) This is working exactly as I want. Commented Oct 10, 2022 at 18:54

You must log in to answer this question.

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