Search code examples
javascriptdatatablevuejs3vue-composition-apiprimevue

How do I keep editor mode ON when detecting invalid data with Primevue's Datatable?


I'm working with Primevue Datatable, it has a row edit mode that let you add a column to control data changes, first it shows a button to turn on edit mode, then when it's on, it shows the save and cancel buttons. So, the component has three events associated with each one.

I want to keep edit mode ON when detecting invalid fields, so user can fill those fields, confirm saving and update data locally before calling a webservice to update changes in the database.

<DataTable editMode="row" @rowEditSave="saveRow">
  <Column :rowEditor="true">
</DataTable>

...

const saveRow = (event) {
  // Validate Data
  if( isDataInvalid(event.data) ) {
    // show Toast error message
   // keep edit mode ON
    event.preventDefault();
  } else {
    // webservice
    updateData( event.data )
  }
}

The problem is that I can't find a way to prevent the save row event from updating wrong data, I've added the "p-invalid" class to indicate invalid fields with a red border, but when I click the save button, it turns off edit mode and locally saves invalid data.

Any help will be apreciated.


Solution

  • According to the documentation:

    "Row Editing is defined by setting cellEdit (I think they mean "editMode") as "row", defining editingRows with the v-model directive to hold the reference to the editing rows and adding a row editor column to provide the editing controls. Note that since editingRows is two-way binding enabled, you may use it to initially display one or more rows in editing more or programmatically toggle row editing."

    So, in your method which handles the @rowEditSave event, do any necessary validation and if the validation fails, assign the data passed in the event back to editingRows:

    saveRow(event) {
      console.log(event.data);
    
      this.editingRows = [...this.editingRows, event.data];
    
      console.log(this.editingRows);
    },
    

    Make sure to specify the v-model editingRows when you configure the datatable:

    v-model:editingRows="editingRows"