Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checkbox won't stay checked on plugin settings page

Tags:

php

wordpress

My checkbox field on a plugin page I wrote won't stay checked. The data is being saved, but the checkbox does not reflect the current stored value (checked).

Here is my function code:

public function jo_checkbox_del_setting()
{
    echo "<input id='jo_checkbox_del' name='jo_plugin_options[jo_checkbox_del]' type='checkbox' value='{$this->options['jo_checkbox_del']}' />";
}

and the add_settings_field code:

add_settings_field('jo_checkbox_del', 'Hide Delete Button: ', array($this, 'jo_checkbox_del_setting'), __FILE__, 'jo_main_section');

enter image description here

as you can see in the picture, the value is 1 which is checked, but the checkbox never stays checked after refresh.

like image 991
Greg L Avatar asked Sep 07 '13 16:09

Greg L


3 Answers

I prefer to use WordPress checked() function with printf() (see the page for sprintf() for usage examples):

printf(
    '<input id="%1$s" name="jo_plugin_options[%1$s]" type="checkbox" %2$s />',
    'jo_checkbox_del',
    checked( isset( $this->options['jo_checkbox_del'] ), true, false )
);
like image 167
brasofilo Avatar answered Sep 30 '22 19:09

brasofilo


use {checked($this->options['jo_checkbox_del']);} inside the <input> element to return checked attribute if the option is set.

I would also recommend on using a hidden input with the same name attribute to handle the case when the option is not checked

public function jo_checkbox_del_setting() {

        echo "<input type='hidden' name='jo_plugin_options[jo_checkbox_del]' value='0' />";

        echo "<input id='jo_checkbox_del' name='jo_plugin_options[jo_checkbox_del]' type='checkbox' value='{$this->options['jo_checkbox_del']}'  {checked($this->options['jo_checkbox_del']);} />";   
}
like image 35
zoranc Avatar answered Sep 30 '22 19:09

zoranc


Use the checked attribute of the checkbox tag instead:

public function jo_checkbox_del_setting()
{
    $checked = ( (int)$this->options['jo_checkbox_del'] == 1 ) ? 'checked' : '';
    echo "<input id='jo_checkbox_del' name='jo_plugin_options[jo_checkbox_del]' type='checkbox' value='{$this->options['jo_checkbox_del']}' $checked />";
}

This is the only way to have a pre-selected checkbox. Setting the value to the stored value will not automatically trigger it to be set.

Also be aware that by default checkboxes in a form will not be sent along at all unless they are checked.

like image 38
Niklas Lindblad Avatar answered Sep 30 '22 19:09

Niklas Lindblad