Dynamically populated checkboxes error in Gravity Forms

1.6k views Asked by At

I have added checkboxes dynamically to Gravity form but when i select last 2 items and click submit i got error message "this field is required". If i select 1st item or 2nd , 3rd then no error and form is submitted successfully.

Here is my php code.

add_filter( 'gform_pre_render_56', 'get_menu_options' );
add_filter( 'gform_pre_validation_56', 'get_menu_options' );
add_filter( 'gform_pre_submission_filter_56', 'get_menu_options' );

function get_menu_options($form){
/****get all beverages from post*****/
$beverages = array_filter( get_post_meta(get_the_ID(), 'wpcf-beverages', false) );

$form['fields'][22]->choices =  set_field_choices($beverages); 

return $form;

}

function set_field_choices($values){
    $field_choices = array();
    $isSelected = (count($values) == 1)?true:false;
    foreach ($values as $value) {
        $field_choices[] = array(
                'text'          => $value,
                'value'         => $value,
                'isSelected'    => $isSelected
            );
    }
    return $field_choices;
}

Here is page link

Thanks

2

There are 2 answers

0
Javid On BEST ANSWER

Ok, i figured out the problem. we need to keep eye on input id

add_filter( 'gform_pre_render_56', 'get_menu_options' );
add_filter( 'gform_pre_validation_56', 'get_menu_options' );
add_filter( 'gform_pre_submission_filter_56', 'get_menu_options' );
add_filter( 'gform_admin_pre_render_56', 'get_menu_options' );

function get_menu_options($form){

$buffetstations1 = array_filter( get_post_meta(get_the_ID(), 'wpcf-buffet-station-1', false) );

foreach ( $form[ 'fields' ] as $key => $field ) {

if( $field->id == 72 ){
         
if( count($buffetstations1) == 0 ){ 
unset ( $form['fields'][$key]); 
}
   $choices = array();
    $inputs = array();
    $field_id = $field->id;
    $input_id = 1;

foreach ( $buffetstations1 as $buffetstation1 ) {
//skipping index that are multiples of 10 (multiples of 10 create problems as the input IDs)

if ( $input_id % 10 == 0 ) {
  $input_id++;
}

$choices[] = array( 'value' => $buffetstation1, 'text' => $buffetstation1 );
$inputs[] = array( 'label' => $buffetstation1, 'id' => "{$field_id}.{$input_id}" );
$input_id++;
}
$field->choices = $choices;
$field->inputs = $inputs;
      
}

}

return $form;

}

0
magic On

It can also be set with the 'form_field_value_$parameter' filter. Given a check box field with choices 'Red', 'Green', 'Blue', 'Yellow' 'Orange' and the allow filed to be populated dynamically parameter: 'color' the following will check the Blue and Green checkbox.

add_filter( 'gform_field_value_color', 'set_checkbox' ); 
function set_checkbox( $form ) {
    return 'Blue,Green'; 
}

I believe this was recently added to gravity forms.