Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Refactoring the Gravity Forms native repeater fields. Read more at https://www.gsarigiannidis.gr/gravity-forms-native-repeater/
<?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
You can’t perform that action at this time.