From 8f6ef456f0566c3ee4b297260527138bbc68ef80 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lucas=20Garc=C3=ADa?= <lucas@codeccoop.org> Date: Mon, 6 May 2024 14:08:39 +0200 Subject: [PATCH] fix: recover fieldset controls --- abstract/class-settings.php | 2 +- includes/fieldset-control-js.php | 49 ++++++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+), 1 deletion(-) create mode 100644 includes/fieldset-control-js.php diff --git a/abstract/class-settings.php b/abstract/class-settings.php index da1c425..e58a4ac 100644 --- a/abstract/class-settings.php +++ b/abstract/class-settings.php @@ -165,7 +165,7 @@ abstract class Settings extends Singleton public function control_render($setting, $field) { $defaults = $this->get_defaults($setting); - $script_path = dirname(__FILE__, 2) . '/assets/js/fieldset-control-js.php'; + $script_path = dirname(__FILE__, 2) . '/includes/fieldset-control-js.php'; ob_start(); ?> <div class="<?= $setting; ?>__<?= $field ?>--controls"> diff --git a/includes/fieldset-control-js.php b/includes/fieldset-control-js.php new file mode 100644 index 0000000..04a4a70 --- /dev/null +++ b/includes/fieldset-control-js.php @@ -0,0 +1,49 @@ +<?php +// Script to be buffered from settings class +$default_value = $defaults[$field][0]; +$is_array = is_array($default_value); +$table_id = $setting . '__' . str_replace('][', '_', $field); +?> + +<script> + (function() { + function renderRowContent(index) { + <?php if ($is_array) : ?> + return `<table id="<?= $table_id ?>_${index}"> + <?php foreach (array_keys($default_value) as $key) : ?> + <tr> + <th><?= $field ?></th> + <td><?= $this->input_render($setting, $field . '][${index}][' . $key, $default_value[$key]); ?></td> + </tr> + <?php endforeach; ?> + </table>`; + <?php else : ?> + return `<?= $this->input_render($setting, $field . '][${index}', $default_value); ?>`; + <?php endif; ?> + } + + function addItem(ev) { + ev.preventDefault(); + const table = document.getElementById("<?= $table_id ?>") + .children[0]; + const tr = document.createElement("tr"); + tr.innerHTML = + "<td>" + renderRowContent(table.children.length) + "</td>"; + table.appendChild(tr); + } + + function removeItem(ev) { + ev.preventDefault(); + const table = document.getElementById("<?= $table_id ?>") + .children[0]; + const rows = table.children; + table.removeChild(rows[rows.length - 1]); + } + + const buttons = document.currentScript.previousElementSibling.querySelectorAll("button"); + buttons.forEach((btn) => { + const callback = btn.dataset.action === "add" ? addItem : removeItem; + btn.addEventListener("click", callback); + }); + })(); +</script> -- GitLab