phpadvanced-custom-fieldscontact-form-7

array of values from acf repeater into cf7 dropdown


I'm trying to populate a cf7 dropdown with values from an acf repeater. If I use a regular hardcoded array, it works just fine so somehow I'm messing up when getting the values of the repeater field.

Here's what I've got rn, trying to push the values into an array:

add_filter('wpcf7_form_tag_data_option', function($n, $options, $args) {
  if (in_array('gigs', $options)){

$gigs = array();
if( have_rows('termine') ):
        while ( have_rows('termine') ) : the_row();
               $gigs[] = get_sub_field('termin');
        endwhile;
endif;
return $gigs;
        
  }
  return $n;

}, 10, 3);

tried moving the return statement around a bit but that didn't help either and I am at a loss with my barely existing php knowledge.

Any ideas or pointers where I'm going wrong would be much appreciated.


Solution

  • You do have to return $n which is either null or a value which would be an array. You are close, but your returning the wrong thing. A good example of how to use this filter is by looking at the code from listo.php an you can see the correct usage of this filter.

    With that said... without testing your ACF values, I can't say if your function will return those... but the below function is tested and will return data to your select with data:gigs if the ACF function works.

    To retrieve the containing post's post_id you need to dig into the unit tag, and get the page id. The global $post won't work inside this filter, as it's not passing any of the loop properties to the function, so you have to specify your ACF field with the second parameter - which needs to be the parent post id.

    add_filter( 'wpcf7_form_tag_data_option', 'dd_filter_form_tag_data', 10, 3 );
    function dd_filter_form_tag_data( $n, $options, $args ) {
        // Get the current form.
        $cf7 = wpcf7_get_current_contact_form();
        // Get the form unit tag.
        $unit_tag = $cf7->unit_tag();
        // Turn the string into an array.
        $tag_array = explode( '-', $unit_tag );
        // The 3rd item in the array will be the page id.
        $post_id = substr( $tag_array[2], 1 );
    
        if ( in_array( 'gigs', $options, true ) ) {
            $gigs = array();
            if ( have_rows( 'termine', $post_id ) ) :
                while ( have_rows( 'termine', $post_id ) ) :
                    the_row();
                    $gigs[] = get_sub_field( 'termin' );
                endwhile;
            endif;
            $n = array_merge( (array) $n, $gigs );
        }
        return $n;
    }