phalcon / cphalcon

High performance, full-stack PHP framework delivered as a C extension.
https://phalcon.io
BSD 3-Clause "New" or "Revised" License
10.79k stars 1.96k forks source link

[BUG]: The empty string is considered null when rendering checkboxes & radios #16648

Open kuhler-Stratege opened 2 months ago

kuhler-Stratege commented 2 months ago

Describe the bug In my project, I created a UI similar to the search page of PHPMyAdmin, where you can filter by different values of an sql table. This is done using several Radiogroups. When the user does not want to filter by a certain column, the value of the radio is an empty string. As default, all entries of an sql table are shown on that page, so per default the Radio with the empty string as value should be selected. \ This is the bug: It does not. When I add an empty string as default and as checked attribute, the Radio is still not checked by default and I need to manually hack the checked flag into the html after rendering.

To Reproduce

Steps to reproduce the behavior:

$options = ['' => 'all', 1 => 'active'];
$html = '';
foreach ($options as $value => $label) {
            $radio = new Radio("IsActive");
            $radio->setLabel($label);
            $radio->setDefault($value);
            $attr['checked'] = '';
            $html .= $radio->render($attr);
}
echo $html;

Expected behavior The rendering of the radio should flag the radio with the empty string as value to be checked if it matches the default or the selected value.

Details

raicabogdan commented 2 months ago

Checking the source code for 'checked' section, I see:

        if checked !== null {
            if !fetch value, attributes["value"] {
                let value = null;
            }
            if checked === value {
                let attributes["checked"] = "checked";
            }
        }

this means that you should be using checked with the same as the value and only on the one you need checked, something like


        $radio1 = new Radio('radio_all', [
            'name' => 'is_active',
            'value' => '',
            'checked' => ''
        ]);
        $radio1->setLabel('All');
        $this->add($radio1);

        $radio2 = new Radio('radio_active', [
            'name' => 'is_active',
            'value' => '1',
        ]);
        $radio2->setLabel('Active');
        $this->add($radio2);