Skip to content

Forms: Add PHP foundation for custom field extensibility#47931

Open
enejb wants to merge 5 commits intotrunkfrom
add/form-fields-php-foundation
Open

Forms: Add PHP foundation for custom field extensibility#47931
enejb wants to merge 5 commits intotrunkfrom
add/form-fields-php-foundation

Conversation

@enejb
Copy link
Copy Markdown
Member

@enejb enejb commented Apr 3, 2026

Fixes #

Proposed changes

  • Add PHP filter hooks to Contact_Form_Field for custom field validation (jetpack_forms_validate_field), rendering (jetpack_forms_render_field), and field type registration (jetpack_forms_field_types)
  • Add jetpack_forms_render_field_value filter to Feedback_Field for custom value rendering across contexts (email, CSV, API, dashboard)
  • Add jetpack_forms_error_types filter to Contact_Form for custom validation error messages
  • Add Form_Field_Registry class providing a unified register() API (similar to register_post_type()) that handles block registration, validation, rendering, error messages, and asset enqueueing in one call
  • Add convenience wrapper functions in form-field-functions.php: register_jetpack_form_field(), unregister_jetpack_form_field(), get_jetpack_form_field()
  • Integrate registered custom field blocks into the Form Editor's allowed block list automatically
  • Add comprehensive PHPUnit tests for both the registry (Form_Field_Registry_Test) and the filter-based extensibility (Field_Extensibility_Test)

Other information

This is PR 1/5 in the stacked custom field extensibility API series:

  1. Forms: Add PHP foundation for custom field extensibility #47931 (this PR) — PHP foundation: filter hooks and Form_Field_Registry
  2. Forms: Add JavaScript Field API for editor integration #47932 — JS/Editor API: block editor integration for custom fields
  3. Forms: Add label support, dashboard hooks, and Interactivity API #47933 — Label, dashboard, and Interactivity API support
  4. Forms: Add asset pipeline and style support for custom fields #47930 — Asset pipeline and style support
  5. Forms: Finalize documentation and changelog #47929 — Documentation and changelog
  • Generate changelog entries for this PR (using AI).

Related product discussion/links

  • Part of the Jetpack Forms custom field extensibility initiative

Does this pull request change what data or activity we track or use?

No changes to tracked data or activity.

Testing instructions

  1. Check out this branch and ensure the Jetpack Forms package is active
  2. Run the PHPUnit tests to verify the registry and extensibility hooks:
    cd projects/packages/forms && composer phpunit -- --filter="Form_Field_Registry_Test|Field_Extensibility_Test"
    
  3. Test manual field registration by adding the following to a plugin or theme's functions.php:
    add_action( 'init', function() {
        if ( function_exists( 'register_jetpack_form_field' ) ) {
            register_jetpack_form_field( 'color', array(
                'validate_callback' => function( $value, $label ) {
                    if ( ! preg_match( '/^#[0-9a-f]{6}$/i', $value ) ) {
                        return sprintf( '%s must be a valid hex color.', $label );
                    }
                    return true;
                },
                'render_field' => function( $data ) {
                    return sprintf(
                        '<input type="color" name="%s" id="%s" value="%s" class="grunion-field" />',
                        esc_attr( $data['id'] ),
                        esc_attr( $data['id'] ),
                        esc_attr( $data['value'] )
                    );
                },
            ) );
        }
    } );
  4. Verify the custom field type appears in Contact_Form_Field::get_registered_field_types()
  5. Verify existing form functionality is not broken — submit a standard form and confirm it still works as expected

enejb and others added 5 commits April 3, 2026 11:04
Add filter hooks to enable external developers to create custom form fields:

- jetpack_forms_validate_field: Custom validation for field types
- jetpack_forms_render_field: Custom frontend field rendering
- jetpack_forms_render_field_value: Custom value rendering for different contexts
- jetpack_forms_field_types: Register custom field types
- jetpack_forms_error_types: Add custom error messages

These filters form the foundation of the field extensibility API.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Add a new class that provides a WordPress-style registration API similar
to register_post_type(). External developers can use register_jetpack_form_field()
to register custom form fields with a single function call.

The registry handles:
- Block registration with PHP
- Validation callback registration
- Frontend field rendering
- Response value rendering for different contexts (email, CSV, API)
- Error message registration
- Editor and dashboard script enqueueing

Global functions added:
- register_jetpack_form_field($type, $args)
- get_jetpack_form_field($type)
- jetpack_form_field_exists($type)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Update Form_Editor to include custom registered field blocks in the
allowed blocks list. This enables custom fields registered via
register_jetpack_form_field() to appear in the block inserter when
editing jetpack-form post types.

Also adds a filter 'jetpack_form_editor_allowed_blocks' for plugins
to add additional blocks to the form editor.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Add comprehensive PHPUnit tests for the field extensibility system:

Form_Field_Registry_Test (38 tests):
- Registration API tests (global functions, validation)
- Filter integration tests (field types, validation, rendering)
- Error message registration tests
- Block name generation tests

Field_Extensibility_Test (19 tests):
- Core filter hook tests for Contact_Form_Field and Feedback_Field
- Integration tests verifying Form_Field_Registry works with existing classes
- End-to-end workflow tests

All tests verify that custom fields can be registered, validated,
and rendered across different contexts (email, CSV, API, dashboard).

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
@github-actions
Copy link
Copy Markdown
Contributor

github-actions bot commented Apr 3, 2026

Are you an Automattician? Please test your changes on all WordPress.com environments to help mitigate accidental explosions.

  • To test on WoA, go to the Plugins menu on a WoA dev site. Click on the "Upload" button and follow the upgrade flow to be able to upload, install, and activate the Jetpack Beta plugin. Once the plugin is active, go to Jetpack > Jetpack Beta, select your plugin (Jetpack), and enable the add/form-fields-php-foundation branch.
  • To test on Simple, run the following command on your sandbox:
bin/jetpack-downloader test jetpack add/form-fields-php-foundation

Interested in more tips and information?

  • In your local development environment, use the jetpack rsync command to sync your changes to a WoA dev blog.
  • Read more about our development workflow here: PCYsg-eg0-p2
  • Figure out when your changes will be shipped to customers here: PCYsg-eg5-p2

@github-actions
Copy link
Copy Markdown
Contributor

github-actions bot commented Apr 3, 2026

Thank you for your PR!

When contributing to Jetpack, we have a few suggestions that can help us test and review your patch:

  • ✅ Include a description of your PR changes.
  • 🔴 Add a "[Status]" label (In Progress, Needs Review, ...).
  • ✅ Add testing instructions.
  • ✅ Specify whether this PR includes any changes to data or privacy.
  • ✅ Add changelog entries to affected projects

This comment will be updated as you work on your PR and make changes. If you think that some of those checks are not needed for your PR, please explain why you think so. Thanks for cooperation 🤖


Follow this PR Review Process:

  1. Ensure all required checks appearing at the bottom of this PR are passing.
  2. Make sure to test your changes on all platforms that it applies to. You're responsible for the quality of the code you ship.
  3. You can use GitHub's Reviewers functionality to request a review.
  4. When it's reviewed and merged, you will be pinged in Slack to deploy the changes to WordPress.com simple once the build is done.

If you have questions about anything, reach out in #jetpack-developers for guidance!

@github-actions github-actions bot added the [Status] Needs Author Reply We need more details from you. This label will be auto-added until the PR meets all requirements. label Apr 3, 2026
@enejb
Copy link
Copy Markdown
Member Author

enejb commented Apr 3, 2026

@claude review this PR.

@claude
Copy link
Copy Markdown
Contributor

claude bot commented Apr 3, 2026

Claude finished @enejb's task in 2m 34s —— View job


PR Review: Forms — Add PHP foundation for custom field extensibility

Tasks:

  • Gather context and understand the request
  • Read changed files
  • Analyze for bugs, security, performance, and conventions
  • Post review feedback

Overall this is well-structured work that follows WordPress conventions closely. The register_post_type() analogy is apt, the docblocks are thorough, and the test coverage is extensive. A few issues worth addressing before merge:


Bug: false return from validate_callback is silently treated as valid

File: class-contact-form-field.php (new default: block)

The filter result handling is:

if ( $custom_validation !== null ) {
    if ( is_string( $custom_validation ) ) {
        $this->add_error( $custom_validation );
    }
    return; // exits validate() regardless
}

If a developer's validate_callback returns false (a natural PHP "failure" value), false !== null so the code enters the block, is_string(false) is false so no error is added, and then it returns — silently treating the field as valid. The docblock says to return true for valid and a string for invalid, but there's no enforcement and false is a common footgun.

Consider adding explicit handling: if ( false === $custom_validation ) { $this->add_error(...); return; }, or at minimum document this edge case prominently. Fix this →


Concern: filter_error_types allows overwriting core error keys

File: class-form-field-registry.php:408

$error_types = array_merge( $error_types, $args['error_messages'] );

Using array_merge where custom fields are merged on top of the existing types means a plugin can inadvertently (or maliciously) overwrite core error messages like is_required, invalid_form, network_error, etc. The same concern applies in class-contact-form.php where apply_filters('jetpack_forms_error_types', ...) results are used directly.

Consider using array_merge($args['error_messages'], $error_types) so core messages take priority, or at least document this behavior. Fix this →


Design gap: No unregister() API

File: class-form-field-registry.php

The PR description draws an analogy to register_post_type(), which has a corresponding unregister_post_type(). There is no unregister() or deregister() method here. Tests work around this with ReflectionClass (lines 52–68 in both test files), which is a red flag — if the tests themselves need reflection to clean up, real consumers will too. This is worth considering even if it ships in a later PR.


_doing_it_wrong() version mismatch

File: class-form-field-registry.php:78,94

_doing_it_wrong( __METHOD__, '...', '1.0.0' );

The forms package is at version 7.15.0. Using '1.0.0' as the "since" version in _doing_it_wrong() is misleading. Jetpack uses '$$next-version$$' as a placeholder that gets substituted at release time — that pattern should be used here too, consistent with the @since $$next-version$$ tags in the same file. Fix this →


Minor: Missing function_exists() guards in form-field-functions.php

File: form-field-functions.php:48,60,72

The three global functions (register_jetpack_form_field, get_jetpack_form_field, jetpack_form_field_exists) have no if ( ! function_exists( '...' ) ) guards. While the file is loaded via require_once, defensive guards are standard for global function files in WordPress plugins/packages and protect against edge cases where the file might be included from another path. Fix this →


Minor: Default script version '1.0.0' may cause stale caches

File: class-form-field-registry.php:109,112

'editor_script_ver'  => '1.0.0',
'dashboard_script_ver' => '1.0.0',

These are the fallback versions when a developer registers a field without specifying a version. If they update their script without bumping the version (easy to forget), browsers will serve cached copies. Defaulting to false (which lets WordPress use the file's modification time) or null would be safer defaults than a fixed string. This is minor since developers are expected to pass their own version, but the default is more footgun than helpful.


Positive notes

  • The overall API design mirrors WordPress conventions well — register_post_type() analogy is clear and the naming is intuitive.
  • The sanitize_key() call on $field_type at registration time is good defensive practice.
  • Handling late registration (after init) with the did_action('init') check and direct register_block() call is thoughtful.
  • The WP_Block_Type_Registry::get_instance()->is_registered() check prevents double-registration.
  • Test coverage across 1,363 lines in two test files is thorough.
  • The jetpack_form_editor_allowed_blocks filter in class-form-editor.php is a nice addition for additional customization.

@jp-launch-control
Copy link
Copy Markdown

Code Coverage Summary

Coverage changed in 5 files.

File Coverage Δ% Δ Uncovered
projects/packages/forms/src/contact-form/class-contact-form-field.php 1156/1845 (62.66%) 0.84% 4 💔
projects/packages/forms/src/contact-form/class-contact-form-plugin.php 603/1520 (39.67%) 0.08% 0 💚
projects/packages/forms/src/contact-form/class-contact-form.php 956/1528 (62.57%) 0.05% 0 💚
projects/packages/forms/src/contact-form/class-feedback-field.php 339/523 (64.82%) 0.69% 0 💚
projects/packages/forms/src/form-editor/class-form-editor.php 75/96 (78.12%) 0.71% 0 💚

2 files are newly checked for coverage.

File Coverage
projects/packages/forms/src/contact-form/form-field-functions.php 0/3 (0.00%) 💔
projects/packages/forms/src/contact-form/class-form-field-registry.php 122/163 (74.85%) 💚

Full summary · PHP report · JS report

If appropriate, add one of these labels to override the failing coverage check: Covered by non-unit tests Use to ignore the Code coverage requirement check when E2Es or other non-unit tests cover the code Coverage tests to be added later Use to ignore the Code coverage requirement check when tests will be added in a follow-up PR I don't care about code coverage for this PR Use this label to ignore the check for insufficient code coveage.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

[Feature] Contact Form [Package] Forms [Status] Needs Author Reply We need more details from you. This label will be auto-added until the PR meets all requirements. [Tests] Includes Tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant