1

I have a datatable in a LWC where I allow users to update fields from the record. I am trying to add validation during save(or does the datatable have its own validation) to make sure 1 field value is not greater than another field. I have not been able to find any documentation or example. here is my .js save

export default class CreateInv extends LightningElement {
@track lineitems = [];
@track data = [];
@track columns = columns;

error;
columns = columns;
@wire(getLineItemList)
lineitems;



handleSave(event) {
    const recordInputs =  event.detail.draftValues.slice().map(draft => {
        const fields = Object.assign({}, draft);
        return { fields };
    });

    const promises = recordInputs.map(recordInput => updateRecord(recordInput));

    Promise.all(promises).then(lineitems => {
        this.dispatchEvent(
            new ShowToastEvent({
                title: 'Success',
                message: 'line Item Updated',
                variant: 'success'
            })
        );
         this.draftValues = [];

         return refreshApex(this.lineitems);
    }).catch(error => {

    });
}

async connectedCallback() {
    const data = await fetchDataHelper({ amountOfRecords: 10 });
    this.data = data;
}

handleclick(){
    var el = this.template.querySelector('lightning-datatable');
    console.log(el);
    var selected = el.getSelectedRows();
    console.log(selected);
} 

 }
2
  • Do you mean a datatable where all inputs have the same value?
    – Klecool
    Jun 1, 2020 at 6:11
  • There will be 2 finance columns rendering in the table, one of them can be edited. When a user enters a value in Column A(editable), it cannot be greater in value than column B.
    – Phuc
    Jun 1, 2020 at 12:54

1 Answer 1

1

You will need the errors attribute in your template to trigger an error on a cell or multiple cells

<template>
    <div class="app slds-p-around_x-large">  
        <br>
    <br>
    <lightning-datatable key-field="id" data={data} columns={columns} draft-values={draftValues} errors={errors}
      oncellchange={handleCellchange} onsave={handleSave}>
    </lightning-datatable>
  </div>
</template>

...

@track draftValues = [];
    @track errors = {};

    columns = [
        {
            label: "Name",
            fieldName: "Name",
        },
        {
            label: "Finance 1",
            fieldName: "finance1",
            editable: true,
            type: 'currency'
        },
        {
            label: "Finance 2",
            fieldName: "finance2",
            type: 'currency'
        }
    ];
    data = [
        { id: '1', Name: 'Account 1', finance1: '1000', finance2: '1500' },
        { id: '2', Name: 'Account 2', finance1: '2000', finance2: '2500' },
        { id: '3', Name: 'Account 3', finance1: '3000', finance2: '3500' },

    ];

    handleCellchange(event) {

        const rowId = event.detail.draftValues[0].id
        console.log("draftValues = ", JSON.stringify(event.detail.draftValues[0]));

        const finance1 = parseFloat(event.detail.draftValues[0].finance1)
        const finance2 = parseFloat(this.data.filter(dat => dat.id === rowId)[0].finance2);

        if (finance1 > finance2) {

            this.triggerError(rowId);
        }

        else if (finance1 < finance2 && this.errors.rows && this.errors.rows[rowId]) {

            this.removeRowError(rowId)
        }
    }

    removeRowError(rowId) {
        if (rowId) {
            delete this.errors.rows[rowId];
        }
    }

    triggerError(rowId) {

        const _errors = {
            rows: {
                ...this.errors.rows, [rowId]: {
                    title: 'Amount 1 must be < to Amount 2.',
                    messages: ['Enter a valid amount.'],
                    fieldNames: ['finance1']
                }
            },
            table: {
                title: 'Your entry cannot be saved. Fix the errors and try again.',
                messages: ['We found 1 error. ...', 'Error on finance1 amount']
            }
        };

        this.errors = _errors;
    }

    handleSave() {
        if (this.errors.rows && Object.keys(this.errors.rows).length === 0) {
            this.errors = {};
        }
        //
    }
8
  • Thanks for the example. I wanted to make sure I understand the code. The data = [] is for example purposes only and not required.
    – Phuc
    Jun 1, 2020 at 19:26
  • No the data = [] is not required, it was just for example purposes only. you will use your real data.
    – Klecool
    Jun 1, 2020 at 19:31
  • Hey Klecool. What is the difference between these 2 lines of code?Want to know so when I need to add more I will understand the why. const finance1 = parseFloat(event.detail.draftValues[0].finance1) const finance2 = parseFloat(this.data.filter(dat => dat.id === rowId)[0].finance2);
    – Phuc
    Jun 1, 2020 at 19:53
  • Those two lines are used to get the value in two columns I want to compare.
    – Klecool
    Jun 1, 2020 at 20:02
  • right. So why is one event.detail.draftValues[0] and the other is this.data.filter(dat => dat.id === rowId)[0]. So if I wanted to add another field to compare which option would I use?
    – Phuc
    Jun 1, 2020 at 20:13

You must log in to answer this question.

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