Search code examples
phpwordpressfunctiongravity-forms-plugingravityforms

function in Gravity Forms to read if a checkbox is checked?


This snippet for Gravity Forms works well with text inputs, verifies that an input is empty and returns the value "Not specified", but appears that it doesn't work with checkboxes.

add_filter( 'gform_pre_submission', 'map_input', 10, 5 );
function map_input( $form ) {
  if (  empty($_POST['input_21']) ) {
    $_POST['input_21'] = 'Not specified';
  }
}

Help would be appreciated :)


Solution

  • Checkboxes have a field ID and input ID. It sounds like you want to check if no checkbox is checked? Here's an simple way to do that:

    // Update "123" to your form ID.
    add_action( 'gform_pre_submission_123', function( $form ) {
    
        // The ID of your checkbox field.
        $field_id = 1;
    
        /** @var GF_Field $field */
        $checkbox_field = GFAPI::get_field( $form, $field_id );
        $value = $checkbox_field->get_value_submission( array() );
    
        // Just so you can see the data that is returned. Delete this once you have.
        print_r( $value );
    
        $value = array_filter( $value );
        if ( empty( $value ) ) {
            // Do what you want to.
        }
    
    } );