Input checkbox or radio button with true/false
Implement a true/false checkbox or radio button input tag that returns the correct value in $_POST
.
http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#method-i-check_box
Checkbox
To prevent a form sending nothing if a checkbox is left blank and thus not being able to change a value from true to false, generate an auxiliary hidden field before the checkbox.
The hidden field has the same name and its attributes mimic an unchecked checkbox. This way, the form either sends only the hidden field (representing the checkbox is unchecked), or both fields.
Since the HTML specification says key/value pairs have to be sent in the same order they appear in the form, and parameters extraction gets the last occurrence of any repeated key in the query string, that works for ordinary forms.
<input type="hidden" name="data[checkbox]" value="0">
<input type="checkbox" name="data[checkbox]" value="1" <?= @$data['checkbox'] ? ' checked' : NULL; ?>>
The disabled
and readonly
attributes will also not be passed to the $_POST
request.
Radio button
In the case of a radio button, the checked
attribute will not affect the value being passed to $_POST
because there are two input tags with the same name,
but disabled
and readonly
will be the reasons to add a hidden input tag before the radio button.
1
is sent to mimic true when not disabled/readonly; 0
is sent to mimic false when disabled/readonly.
<input type="hidden" name="data[radio]" value="<?= $is_disabled ? '0' : '1'; ?>">
<input type="radio" name="data[radio]" value="1" <?= @$data['radio'] ? 'checked' : NULL; ?> <?= $is_disabled ? 'disabled' : NULL; ?>>
<input type="radio" name="data[radio]" value="0" <?= @$data['radio'] ? NULL : 'checked'; ?> <?= $is_disabled ? 'disabled' : NULL; ?>>