Created
June 30, 2019 14:27
-
-
Save gsarig/e627decb89a5d2cc6d621e5920b053d3 to your computer and use it in GitHub Desktop.
Refactoring the Gravity Forms native repeater fields. Read more at https://www.gsarigiannidis.gr/gravity-forms-native-repeater/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$form_id = 3; | |
add_filter( 'gform_form_post_get_meta_' . $form_id, 'add_repeater_field' ); | |
function add_repeater_field( $form ) { | |
$field_id = 1000; | |
$fields = [ | |
GF_Fields::create( | |
[ | |
'type' => 'text', | |
'id' => $field_id += 1, | |
'formId' => $form['id'], | |
'label' => __( 'Field 1', 'theme-prefix' ), | |
'pageNumber' => 1, | |
] | |
), | |
GF_Fields::create( | |
[ | |
'type' => 'text', | |
'id' => $field_id += 1, | |
'formId' => $form['id'], | |
'label' => __( 'Field 2', 'theme-prefix' ), | |
'pageNumber' => 1, | |
] | |
), | |
GF_Fields::create( | |
[ | |
'type' => 'select', | |
'id' => $field_id += 1, | |
'formId' => $form['id'], | |
'label' => __( 'Field 3 (dropdown)', 'theme-prefix' ), | |
'choices' => [ | |
[ | |
'text' => 'Option 1', | |
'value' => 'option_1', | |
'isSelected' => true, | |
], | |
[ | |
'text' => 'Option 2', | |
'value' => 'option_2', | |
'isSelected' => false, | |
], | |
[ | |
'text' => 'Option 3', | |
'value' => 'option_3', | |
'isSelected' => false, | |
], | |
], | |
'pageNumber' => 1, | |
] | |
), | |
]; | |
$repeater = GF_Fields::create( | |
[ | |
'type' => 'repeater', | |
'description' => __( 'Maximum of 3 team members - set by the maxItems property', 'theme-prefix' ), | |
'id' => $field_id, | |
'formId' => $form['id'], | |
'label' => __( 'Team Members', 'theme-prefix' ), | |
'addButtonText' => __( 'Add team member', 'theme-prefix' ), | |
'removeButtonText' => __( 'Remove team member', 'theme-prefix' ), | |
'maxItems' => 5, | |
'pageNumber' => 1, | |
'fields' => $fields, | |
] | |
); | |
$repeater_exists = false; | |
foreach ( $form['fields'] as $field ) { | |
if ( 'repeater' === $field->type && $field->id === $field_id ) { | |
$repeater_exists = true; | |
} | |
} | |
if ( ! $repeater_exists ) { | |
$form['fields'][] = $repeater; | |
} | |
return $form; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment