From f4f9dfe0720c524c92c735f95ee6784146c59d92 Mon Sep 17 00:00:00 2001 From: Yuri Dimas Date: Wed, 17 Dec 2025 12:42:46 +0700 Subject: [PATCH] feat: add dynamic form --- Views/Transaksi/Nasabah/Index.cshtml | 121 +++++++++++++++++++++------ 1 file changed, 95 insertions(+), 26 deletions(-) diff --git a/Views/Transaksi/Nasabah/Index.cshtml b/Views/Transaksi/Nasabah/Index.cshtml index ccb0936..2474aab 100644 --- a/Views/Transaksi/Nasabah/Index.cshtml +++ b/Views/Transaksi/Nasabah/Index.cshtml @@ -58,36 +58,40 @@
-
-
-
- - Jenis Sampah - * - - -
-
+
-
-
- - Berat Sampah (Kg) - * - - -
-
+
- @@ -206,10 +210,14 @@ // Populate form with row data $('#nama').val(row.nama); + setSampahRows(row && row.detail_sampah ? row.detail_sampah : []); // Open modal modal_tambah.showModal(); }); + + // initialize dynamic sampah fields + setSampahRows(); }); function closeModal() { @@ -217,6 +225,7 @@ $('#formTambah')[0].reset(); $('#edit_mode').val('false'); $('#modal_title').text('Tambah Fasilitas'); + setSampahRows(); // Close modal modal_tambah.close(); @@ -244,5 +253,65 @@ table.ajax.reload(); }); } + + function setSampahRows(items) { + var container = document.getElementById('sampahFields'); + if (!container) return; + container.innerHTML = ''; + + if (items && items.length) { + items.forEach(function (item) { addSampahRow(item); }); + } else { + addSampahRow(); + } + } + + function addSampahRow(data) { + var template = document.getElementById('jenisSampahRowTemplate'); + var container = document.getElementById('sampahFields'); + if (!template || !container) return; + + var clone = template.content.firstElementChild.cloneNode(true); + var jenisSelect = clone.querySelector('select[name="jenis_sampah[]"]'); + var beratInput = clone.querySelector('input[name="berat_sampah[]"]'); + + if (data && jenisSelect) { + var jenisValue = data.jenis_sampah_id || data.jenis_sampah; + if (jenisValue) jenisSelect.value = jenisValue; + } + + if (data && beratInput && (data.berat !== undefined || data.jumlah_berat !== undefined)) { + beratInput.value = data.berat || data.jumlah_berat; + } + + container.appendChild(clone); + updateSampahRemoveButtons(); + } + + function removeSampahRow(button) { + var container = document.getElementById('sampahFields'); + if (!container) return; + + var row = button.closest('.sampah-row'); + if (row) { + row.remove(); + updateSampahRemoveButtons(); + } + } + + function updateSampahRemoveButtons() { + var container = document.getElementById('sampahFields'); + if (!container) return; + + var rows = container.querySelectorAll('.sampah-row'); + var disableRemove = rows.length <= 1; + + rows.forEach(function (row) { + var btn = row.querySelector('.btn-remove-sampah'); + if (!btn) return; + btn.disabled = disableRemove; + btn.classList.toggle('btn-disabled', disableRemove); + }); + } }