Gravity Forms: Create fields programmatically

Is there any possiblity to create and manage gravity fields dynamically?
I have form with ID 4 with couple fields. I want to add some fields of type checkbox with my own custom external data which can change in time and can be in many instance (not countable, today it can be 1 field, tommorow it could be 3 fields), so I can’t add this fields permanently in form settings in admin panel. I try to follow gform_pre_render filter doucmentation and some other SO questions like How to add Gravity Forms fields in gform_pre_render() but I’m stuck in some validation issues. Newly created fields should be required and when I try to submit the form this dynamically created fields get duplicates and half of them are red-marked required and the other half is not marked as required. Below are the code

add_filter( 'gform_pre_render_4', 'populate_checkbox' );
add_filter( 'gform_pre_validation_4', 'populate_checkbox' );
add_filter( 'gform_pre_submission_filter_4', 'populate_checkbox' );

$count = 101;
if($query->have_posts()) {
    while($query->have_posts()) {
        ++$count;
        $query->the_post();
        $required = get_post_meta($query->post->ID, 'required', true);

        $choices = array( array( 'text' => $query->post->post_content, 'value' => $query->post->ID ) );
        $inputs = array( array( 'label' => $query->post->post_content, 'id' => "{$count}" ) );
        
        $props = array( 
            'id' => $count,
            'clause' => $query->post->ID,
            'choices' => $choices,
            'inputs' => $inputs,
            'isRequired' => (bool) $required,
            'label' => 'My Field Label',
            'type' => 'checkbox'
        );
        $field = GF_Fields::create( $props );
        array_push( $form['fields'], $field );
    }
}

Any clues will be much appreciate!

0

Leave a Comment