WordPress-Plugin-Template icon indicating copy to clipboard operation
WordPress-Plugin-Template copied to clipboard

Checkbox form error

Open LoonSongSoftware opened this issue 4 years ago • 0 comments

The boilerplate template code's Admin page/"Input Examples" tab doesn't work for me.

The initial display is fine but, when a setting is changed and saved, the next time the page is displayed, an error is generated on the backend. I think this is because all of these settings are initially provided (and stored in the wp_options table) as a 5-element array.

But, when "save settings" is pressed, the resulting $_POST value includes only a 4-element array--the checkbox input item is ignored. And, since the $_POST indicates that the values should be updated, the 5-element array in the wp_options table is overwritten with this 4-element array. Henceforward, any attempt to access the combobox setting will fail, since the old value has been overwritten/deleted.

One way to address the issue is to make another "hidden" tag in the form to represent the checkbox.

Another is to just test for existence of that array element before using it. Here's a re-written version of xxxxxxxxxxxxxx that adds this check:

public function checkboxElementCallback(): void
{
    // We update the name attribute to access this element's ID in the context of the display options array.
    // We also access the show_header element of the options collection in the call to the checked() helper function.
    if (array_key_exists($this->checkboxExampleId,$this->exampleOptions)) {
        $itemChecked = checked($this->exampleOptions[$this->checkboxExampleId], true, false);
    } else {
        $itemChecked = false;
    }
    $html = sprintf('<input type="checkbox" id="%s" name="%s[%s]" value="%s" %s />', $this->checkboxExampleId, $this->exampleOptionName, $this->checkboxExampleId, $itemChecked?'1':'0', $itemChecked);
    $html .= '&nbsp;';

    // Here, we'll take the first argument of the array and add it to a label next to the checkbox
    $html .= sprintf('<label for="%s">This is an example of a checkbox</label>', $this->checkboxExampleId);

    echo $html;
}

Thoughts?

LoonSongSoftware avatar Feb 23 '21 19:02 LoonSongSoftware