From 9a73311a992773956bd311cc2577572b74ba4cee Mon Sep 17 00:00:00 2001 From: Marcus Moore Date: Thu, 22 Aug 2024 17:04:04 -0700 Subject: [PATCH] Fix nested checkboxes being updated as a group --- .../CustomFieldSetDefaultValuesForModel.php | 38 +++++++++++++++++-- 1 file changed, 35 insertions(+), 3 deletions(-) diff --git a/app/Livewire/CustomFieldSetDefaultValuesForModel.php b/app/Livewire/CustomFieldSetDefaultValuesForModel.php index fb6df3a3cf..0ca733eb24 100644 --- a/app/Livewire/CustomFieldSetDefaultValuesForModel.php +++ b/app/Livewire/CustomFieldSetDefaultValuesForModel.php @@ -24,9 +24,8 @@ class CustomFieldSetDefaultValuesForModel extends Component $this->fieldset_id = $this->model?->fieldset_id; $this->add_default_values = ($this->model?->defaultValues->count() > 0); - $this->fields->each(function ($field) { - $this->selectedValues[$field->db_column] = $this->getSelectedValueForField($field); - }); + $this->initializeSelectedValuesArray(); + $this->populatedSelectedValuesArray(); } #[Computed] @@ -52,6 +51,39 @@ class CustomFieldSetDefaultValuesForModel extends Component return view('livewire.custom-field-set-default-values-for-model'); } + /** + * Livewire property binding plays nicer with arrays when it knows + * which keys will be present instead of them being + * dynamically added (this is especially true for checkboxes). + * + * Let's go ahead and initialize selectedValues with all the potential keys (custom field db_columns). + * + * @return void + */ + private function initializeSelectedValuesArray(): void + { + CustomField::all()->each(function ($field) { + $this->selectedValues[$field->db_column] = null; + + if ($field->element === 'checkbox') { + $this->selectedValues[$field->db_column] = []; + } + }); + } + + /** + * Populate the selectedValues array with the + * default values or old input for each field. + * + * @return void + */ + private function populatedSelectedValuesArray(): void + { + $this->fields->each(function ($field) { + $this->selectedValues[$field->db_column] = $this->getSelectedValueForField($field); + }); + } + private function getSelectedValueForField(CustomField $field) { $defaultValue = $field->defaultValue($this->model_id);