Support

Account

Home Forums Front-end Issues Combine values from checkboxes and text/repeater fields Reply To: Combine values from checkboxes and text/repeater fields

  • Here’s where I’m starting to build the form: make a list of checkboxes from previous answers and assign them to the $checkboxes[] variable.

    if ( $poll_responses->have_posts() ) :
        while ( $poll_responses->have_posts() ) :
            $poll_responses->the_post();
            if ( have_rows( 'poll_answer', get_the_ID() ) ) :
                while ( have_rows( 'poll_answer', get_the_ID() ) ) :
                    the_row();
                    // print checkboxes for each existing answer
                    echo '<input type="checkbox" name="checkboxes[]" ';
                    echo 'value="' . get_sub_field( 'answer', get_the_ID() ) . '">';
                endwhile;
            endif;
        endwhile;
        wp_reset_postdata();
    endif;
    
    // text or repeater field to add your own custom poll answer
    // (this part works fine, values added as expected, show up in list of previous answers)

    Then I save the checkbox answers and the new custom answers:

    function dutchtown_save_poll_response( $post_id )
    {
        if ( get_post_type( $post_id ) !== 'poll_response' ) : return; endif;
    	if ( is_admin() ) : return; endif;
        
    	$post = get_post( $post_id );
    
        if ( have_rows( 'poll_answer', $post_id ) ) :
            while ( have_rows( 'poll_answer', $post_id ) ) :
                the_row();
                $answer[] = get_sub_field( 'answer', $post_id );
            endwhile;
        endif;
    
        if ( ! empty( $_POST['checkboxes'] ) ) :
            for ( $i = 0; $i < count( $_POST['checkboxes'] ); $i++ ) :
                if ( $_POST['checkboxes'][$i] != '' ) :
                    add_row( 'poll_answer', array( 'answer' => $_POST['checkboxes'][$i] ) );
                endif;
            endfor;
        endif;
    }

    The custom answers show correctly when the list is refreshed. The checkbox answers get inserted into the database, but show as blank both in the new checkbox list and when I go to look at the created post in wp-admin. I’m not sure where the disconnect is—or if I’m going about this all wrong.