mardi 14 juin 2022

Sending unchecked multiple checkboxes

I'm adding multiple checkboxes to a form in Wordpress that lets you check and uncheck certain features that a user should have, saved as a meta field value on the particular user in question that you're editing when submitting the form. I have set up a "user edit page" for this, so that you can make these edits directly on the front end.

The problem, that I understand is quite common but that I still couldn't find answers for in my specific case, is that unchecked boxes doesn't get sent by the form.

Let's say for example that the there would be multiple checkboxes with the same name like this:

<label><input type="checkbox" name="meta[entity_access][]" value="entity1" />Entity 1</label>
<label><input type="checkbox" name="meta[entity_access][]" value="entity2" />Entity 2</label>
<label><input type="checkbox" name="meta[entity_access][]" value="entity2" />Entity 3</label>

If I were to check any of these boxes and submit the form, that checkbox would then already be checked when I edit the user another time. But if I then uncheck the same checkbox and send the form, returning to the user edit page it would still be checked, since the form isn't sending unchecked boxes.

I have seen solutions where you would have a hidden field for each of the checkboxes, with 0 as the value:

<input type="hidden" name="meta[entity_access][]" value="0" />
<label><input type="checkbox" name="meta[entity_access][]" value="entity1" />Entity 1</label>

But wouldn't that leave a lot of zeroes in the array of the meta[entity_access][]?

In the end, I would like the meta[entity_access][] array to contain the checkbox values that have been checked. And if a value gets unchecked, it should remove that value from the array. So using the example above, if all checkboxes apart from entity1 were unchecked, it would return an array only containing entity1. If I then uncheck entity1 and submit again, the field should return an empty array.




Aucun commentaire:

Enregistrer un commentaire