通过代码的方式增加Gravity Forms 字段, 本案例增加了 repeater 重复器。字段可以增加到已存的表单里面。


$form_id = 1; //增加到指定的表单
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' => 'select',
'id' => $field_id += 1,
'formId' => $form['id'],
'label' => __( '尺寸', 'theme-prefix' ),
'choices' => [
[
'text' => 'XS',
'value' => 'XS',
'isSelected' => true,
],
[
'text' => 'S',
'value' => 'S',
'isSelected' => false,
],
[
'text' => 'M',
'value' => 'M',
'isSelected' => false,
],
[
'text' => 'L',
'value' => 'L',
'isSelected' => false,
],
[
'text' => 'XL',
'value' => 'XL',
'isSelected' => false,
],
[
'text' => 'XXL',
'value' => 'XXL',
'isSelected' => false,
],
[
'text' => 'XXXL',
'value' => 'XXXL',
'isSelected' => false,
],
],
'pageNumber' => 1,
]
),
//创建数量字段-数字
GF_Fields::create(
[
'type' => 'number',
'id' => $field_id += 1,
'formId' => $form['id'],
'label' => __( '數量', 'theme-prefix' ),
'pageNumber' => 1,
]
),
];
//创建重复器
$repeater = GF_Fields::create(
[
'type' => 'repeater',
'description' => __( '', 'theme-prefix' ),
'id' => $field_id,
'formId' => $form['id'],
'label' => __( '', 'theme-prefix' ),
'addButtonText' => __( '+新增尺寸', 'theme-prefix' ),
'removeButtonText' => __( '—', 'theme-prefix' ),
'maxItems' => 10,
'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;
}

原文章 https://www.gsarigiannidis.gr/gravity-forms-native-repeater/
Gravity Forms官方文档repeater字段说明: https://docs.gravityforms.com/repeater-fields/