Settings API – Undefined Index when unchecking checkbox

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.

3 Answers
3

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

}

Leave a Comment