bookmark_borderHow to set the Default Properties for a New Field

Introduction

Historically it’s been possible to set the default properties for a new field by using the autolink_gform_editor_js_set_default_values hook to echo a custom case into the switch statement within the SetDefaultValues() function in js.php, however, it’s also been possible to define your own SetDefaultValues{$type} function instead. In this article we will show how you can use that function in your new field which extends the GF_Field class.

## The SetDefaultValues_{$type} function

Here’s what a basic SetDefaultValues_ function would look like, the function name ends with your field type, in this case the field type is simple. The function is passed the field object so you can set the default values of any of the properties, in this case we are setting the field label.

function SetDefaultValues_simple(field) {
    field.label = 'The Default Field Label Goes Here';
}

See the Field Object article for the standard field properties.

## Using get_form_editor_inline_script_on_page_render()

The GF_Field class includes the get_form_editor_inline_script_on_page_render() method which can be used to include scripts in the form editor. In this example we are assigning the value returned by the get_form_editor_field_title() method as the default label for new fields of this type.

public function get_form_editor_inline_script_on_page_render() {

	// set the default field label for the field
	$script = sprintf( "function SetDefaultValues_%s(field) {field.label = '%s';}", $this->type, $this->get_form_editor_field_title() ) . PHP_EOL;

	return $script;
}

Setting the default Choices

You can use the Choice() function when defining the fields default choices.

new Choice(text, value, price)

The value and price properties are optional, if a value is not specified the text will be assigned to the choice value.

Here’s an example showing how that can be used with the SetDefaultValues_ function.

function SetDefaultValues_simple(field) {
    field.label = 'The Default Field Label Goes Here';
    field.choices = [new Choice('Your First Choice'), new Choice('Your Second Choice'), new Choice('Your Third Choice')];
}

Setting the default Inputs

You can use the Input() function when defining the fields default inputs.

new Input(id, label)

The id is a string in the format {field_id}.{input_number}, starting with the input_number of 1. For example, the first input of field 5 would be 5.1. We also recommend skipping ids ending in zero, so you would skip 5.10, 5.20 etc.

Here’s an example showing how that can be used with the SetDefaultValues_ function.

function SetDefaultValues_simple(field) {
    field.label = 'The Default Field Label Goes Here';
    field.inputs = [new Input(field.id + '.1', 'Your First Choice'), new Input(field.id + '.2', 'Your Second Choice'), new Input(field.id + '.3', 'Your Third Choice')];
}