sitecrafting / conifer

:evergreen_tree: A powerful WordPress library plugin for OO development
https://www.coniferplug.in
MIT License
18 stars 2 forks source link

Forms treat falsey field values as null #129

Closed acobster closed 3 years ago

acobster commented 4 years ago

Expected behavior

Say you have a field my_field with a value of "0":

<input type="radio" name="my_field" value="0">

Assuming you declare this field server-side in your form class, you might expect that if the user checks that input, you'd get this:

$form->get('my_field');
// -> "0"

Actual behavior

Instead, you get null because of the more lenient ?: operator in the filter_field() method:

    // fallback on configured default, if any
    $value = $value ?: $field['default'] ?? null;

"0" is falsey, so the field value is falling back to the field default, if it exists, and otherwise to null. We should honor any non-null value here by using the ?? operator instead of ?:.

acobster commented 3 years ago

Slight adjustment - the correct logic is actually:

$value = $value ?: $field['default'] ?? $value;

This is because we do want ?: to carry forward falsey values including null, but we still need the ?? $value after in case $value is falsey AND the default is not set.