Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Checkbox form error #20

Open
LoonSongSoftware opened this issue Feb 23, 2021 · 0 comments
Open

Checkbox form error #20

LoonSongSoftware opened this issue Feb 23, 2021 · 0 comments

Comments

@LoonSongSoftware
Copy link

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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant