2

I know this may be a duplicate however I haven't been able to make sense of previous questions.

I have a checkbox on a settings page. Everything is okay on the first load of the page, if I check the box and save all is fine. If I then uncheck i get the following error:

Notice: Undefined index: dat_checkbox_field_0 in .../wp-content/plugins/divi-auto-testimonials/admin/dat-options.php on line 49 value='1'>

The function:

function dat_checkbox_field_0_render(  ) { 

    $options = get_option( 'dat_settings' );
    ?>
    <input type='checkbox' name='dat_settings[dat_checkbox_field_0]' <?php checked( $options['dat_checkbox_field_0'], 1 ); ?> value='1'>
    <?php

}

Line 49 is the input html.

I also get the same error for this code:

$options = get_option( 'dat_settings' );
if( $options['dat_checkbox_field_0'] != '1' ) {
 include_once "admin/notification.php";
}

From what I understand I need to set the value as null I think but I am not entirely sure if that is correct and if so how.

  • Use isset to verify that key exists in the array. – leninhasda Sep 18 '16 at 18:00
  • Where abouts would I do that though? – Ben H Sep 18 '16 at 18:05
2

Managed to fix this by doing the following:

function dat_checkbox_field_0_render(  ) { 

    $options = get_option( 'dat_settings' );
    $a = $options;
if (array_key_exists("dat_checkbox_field_0",$a))
  { } else { 
    $options['data_checkbox_field_0'] = false;
  }
    ?>
      <input type='checkbox' name='dat_settings[dat_checkbox_field_0]' <?php checked( $options['dat_checkbox_field_0'], 1 ); ?> value='1'>
    <?php

}
  • if( ! isset($options['data_checkbox_field_0']) ) { $options['data_checkbox_field_0'] = false; } – leninhasda Sep 19 '16 at 6:27
2
$options = get_option( 'dat_settings' );
$options['dat_checkbox_field_0'] = empty( $options['dat_checkbox_field_0'] ) ? 0 : 1;

Basically, if the variable is "empty", meaning that it is not set, or that it is equal to false (zero qualifies), then it will be assigned the value of 0. If it's set to true or equivalent (one qualifies) then it will be assigned the value of 1.

Alternatively, reverse the logic for the same result (for purists who like true to come first in ternary statements):

$options['dat_checkbox_field_0'] = !empty( $options['dat_checkbox_field_0'] ) ? 1 : 0;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.