Users cannot add rows with the same item twice. If do, then show an error message and remove the row/item from row

I have a vehicle price doctype. In this doctype, I have a child table that has two field names (vehicle item, item price). Users can add multiple rows but when a duplicate row is added then it should remove and show an error message. Please give me some guidance on how to resolve it.

1 Like

@shuvro-baset You can achieve that through creating a Client Script on the Vehicle doctype form and the script should be on the child table doctype.

Assuming that:

  • Child table doctype: Vehicle Item
  • Child table fieldname in main doctype: vehicle_items
  • Child table field to check: vehicle_item

Then the code can be something like the following.

frappe.ui.form.on("Vehicle Item", {
        vehicle_items_add: function(frm, cdt, cdn) {
            $.each(locals[cdt][cdn].vehicle_items, function(row) {
                if (row.vehicle_item === cdt.vehicle_item) {
                    frappe.msgprint({
                        title: __('Duplicated Item'),
                        indicator: 'red',
                        message: __('The item you added already exist in the table.')
                    });
                    frappe.model.delete_doc(cdt, cdn);
                    frm.refresh_field('vehicle_items');
                    return false;
                }
            });
        }
});
1 Like

Thank you, it works. But duplicate item did not remove. Don’t know whats the matter

@shuvro-baset How about you try replacing

frappe.model.remove_from_locals(cdt, cdn);

with

frappe.model.delete_doc(cdt, cdn);

and see if it works.

It’s not worked for me. I am using frappe version 14. My Alternate solution is

// change Parent DocType
frappe.ui.form.on('Parent DocType', {
  validate: function (frm) {
    var existingValues = [];
    var duplicatesFound = false;

    // change child_table . Iterate through the child table rows
    frm.doc.child_table.forEach(function (row) {
       // change unique_field
      var fieldValue = row.unique_field;

      if (existingValues.indexOf(fieldValue) !== -1) {
        // Duplicate value found
        duplicatesFound = true;
        frappe.msgprint(__('Duplicate value in child table: {0}', [fieldValue]));
        frappe.validated = false; // Prevent saving
        return false; // Exit the loop
      }

      existingValues.push(fieldValue);
    });

    if (!duplicatesFound) {
      frappe.validated = true; // No duplicates found, allow saving
    }
  },
});
1 Like