Get the existing form.
// Replace "123" with your existing form ID. $form = GFAPI::get_form( 123 );
Determine the new field’s ID.
If only one new field is being added AND the Gravity Forms version being used is at least 2.4.7, the easiest way to get the next field ID is as follows:
//works if only one field being added //must have at least Gravity Forms version 2.4.7 $new_field_id = GFFormsModel::get_next_field_id( $form['fields'] );
Otherwise, use this method:
Loop through the existing form fields to get the highest existing field ID. Increase that number by one to get the next available field ID.
$new_field_id = 0; foreach( $form['fields'] as $field ) { if( $field->id > $new_field_id ) { $new_field_id = $field->id; } } $new_field_id++;
Create a new field object.
//create an array of field properties, this example creates a text field //pass array to the create method $properties['type'] = 'text'; $field = GF_Fields::create( $properties );
Set new field’s properties.
If only adding one new field, the properties may be set along with the type property set when calling GF_Fields::create() in the step above:
$properties['id'] = $new_field_id; $properties['label'] = 'My Field';
Othewise, follow this step.
Set the field’s id
property to the $new_field_id
variable. Set the field’s label
property as desired. Set any other desired field properties here.
$field->id = $new_field_id; $field->label = 'My New Field';
Add the new field to the form object.
$form['fields'][] = $field;
Save the modified form object.
GFAPI::update_form( $form );