Home › Forums › Front-end Issues › Combine values from checkboxes and text/repeater fields
I am setting up a poll with a front end form. I would like to show a list of checkboxes of possible answers, and then also a text or repeater field to add your own answers.
Once someone has added an answer, I would like that answer to be given its own checkbox in the list for future participants to be able to choose. So, the manually entered answer from the text/repeater field would then become a value for the list of checkboxes.
I apologize if this question is too vague or conceptual, but I don’t even know where to start with the code to bring the checkbox fields in the text/repeater fields together. Any help is appreciated!
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.
Do do this you need to create an acf/save_post action.
You must be logged in to reply to this topic.
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.