bookmark_borderHow to add a Custom Field Group when using the Field Framework

Introduction

Back in the day you could use the gform_add_field_buttons filter to add the buttons for custom fields and add custom field groups.

With the introduction of the GF_Field class adding a field to an existing group is a simple as overriding the get_form_editor_button() method. But what about adding the field button to a custom group?

Introducing the add_button() method.

The add_button() method

GF_Field::add_button() is responsible for adding the field button to the group specified in the array returned by get_form_editor_button(), however, if the group does not exist the button won’t be added.

If you were to use the gform_add_field_buttons filter to add your custom group you would find the group is added but your new field isn’t added to the group, that’s because the filter runs after the fields are added to the groups. You could update your function hooked to the gform_add_field_buttons filter to also add the button to the group but what would be the fun in that.

The following example shows how you can override the add_button() method to include a custom group if it doesn’t already exist.

/**
 * Adds the field button to the specified group.
 *
 * @param array $field_groups The field groups containing the individual field buttons.
 *
 * @return array
 */
public function add_button( $field_groups ) {
	$field_groups = $this->maybe_add_field_group( $field_groups );

	return parent::add_button( $field_groups );
}

And here’s the function which actually performs the check and then returns the updated array of groups.

/**
 * Adds the custom field group if it doesn't already exist.
 *
 * @param array $field_groups The field groups containing the individual field buttons.
 *
 * @return array
 */
public function maybe_add_field_group( $field_groups ) {
	foreach ( $field_groups as $field_group ) {
		if ( $field_group['name'] == 'your_custom_group_name' ) {

			return $field_groups;
		}
	}

	$field_groups[] = array(
		'name'   => 'your_custom_group_name',
		'label'  => __( 'The Group Label', 'simplefieldaddon' ),
		'fields' => array()
	);

	return $field_groups;
}

Now when you your get_form_editor_button() function looks like this your field button will be added to the custom group.

/**
 * Assign the field button to the custom group.
 *
 * @return array
 */
public function get_form_editor_button() {
	return array(
		'group' => 'your_custom_group_name',
		'text'  => $this->get_form_editor_field_title(),
	);
}