Skip to content

Forms: conditional logic (4/5) — server-side render and validation - #50979

Open
enejb wants to merge 6 commits into
add/forms-conditional-logic-frontendfrom
add/forms-conditional-logic-server
Open

Forms: conditional logic (4/5) — server-side render and validation#50979
enejb wants to merge 6 commits into
add/forms-conditional-logic-frontendfrom
add/forms-conditional-logic-server

Conversation

@enejb

@enejb enejb commented Jul 31, 2026

Copy link
Copy Markdown
Member

Fixes FORMS-748

Part 4 of 5. This series splits #50938 into reviewable pieces. Each PR is based on the previous one, so the diff shown here is incremental.

  1. Forms: conditional logic (1/5) — vocabulary and feature flag #50976 — vocabulary and feature flag
  2. Forms: conditional logic (2/5) — the resolver, in JS and PHP #50977 — the resolver, in JS and PHP
  3. Forms: conditional logic (3/5) — apply in the browser #50978 — apply in the browser
  4. Forms: conditional logic (4/5) — server-side render and validation #50979 — server-side render and validation
  5. Forms: conditional logic (5/5) — the editor panel #50980 — the editor panel

Proposed changes

Part 4 of 5 splitting #50938. Two problems the browser cannot solve on its own.

A required field that conditional logic hides used to block submission. It was invalid, but the visitor could not see it to fill it in. Validation now skips fields the rules hide, evaluated server-side from the submitted values rather than trusting anything the browser reports. Parse-time validation is deferred for conditional fields, which otherwise wrote a static error before any answers existed.

Fields that start hidden used to render visible and then disappear once the runtime booted. Initial visibility is now resolved while rendering and stamped onto the markup, so the form is correct in its first paint. Values prefilled through the query string are taken into account, so a link that prefills the field a rule depends on renders the resulting state directly.

Only hidden fields are dropped from the stored feedback, so a response records what the visitor was actually asked.

Related product discussion/links

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

A form response no longer stores values for fields that conditional logic hid at submit time. Nothing new is collected.

Testing instructions

With the flag on and a form that hides a required field:

  • Submit without revealing the hidden required field → submission succeeds, no error about a field you cannot see.
  • Reveal it, leave it empty, submit → validation fails as normal.
  • Load a form whose first field is hidden by a rule → it must not flash visible before disappearing. Throttle the network to make a flash obvious.
  • Load the same form with ?fieldname=value prefilling the field a rule depends on → the dependent field renders in its resulting state immediately.
  • Check the stored response contains only fields that were visible.

Also: jetpack test php packages/forms.

@github-actions

github-actions Bot commented Jul 31, 2026

Copy link
Copy Markdown
Contributor

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/forms-conditional-logic-server branch.
  • To test on Simple, run the following command on your sandbox:
bin/jetpack-downloader test jetpack add/forms-conditional-logic-server

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

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!

@jp-launch-control

jp-launch-control Bot commented Jul 31, 2026

Copy link
Copy Markdown

Code Coverage Summary

No summary data is available for parent commit d26e859, so cannot calculate coverage changes. 😴

If that commit is a feature branch rather than a trunk commit, this is expected. Otherwise, this should be updated once coverage for d26e859 is available.

Full summary · PHP report · JS report

@enejb
enejb force-pushed the add/forms-conditional-logic-server branch from aec5512 to 9358fbb Compare August 4, 2026 18:36
@enejb
enejb force-pushed the add/forms-conditional-logic-server branch from 9358fbb to 3336b8a Compare August 10, 2026 22:28
Problems the browser cannot solve on its own.

A required field that conditional logic hides used to block submission: it was
invalid, but the visitor could not see it to fill it in. Validation now skips
fields the rules hide, evaluated server-side from the submitted values rather
than trusting anything the browser reports. Parse-time validation is deferred
for conditional fields, which otherwise wrote a static error before any answers
existed -- and every submission path now validates once the form is whole, which
the legacy path did not.

Fields that start hidden used to render visible and then disappear once the
runtime booted. Initial visibility is resolved while rendering and stamped onto
the markup, on the element that holds the field's slot in the row, so the form is
correct in its first paint and the row does not keep a hole. Values prefilled
through the query string are taken into account.

Validation and storage consult one resolution rather than resolving separately
over different value sources, and a hidden field's answer is stripped once on
the way in -- so the stored response, the comment content, the consent flag, the
author details and the integrations all agree that it was never answered.

The rules survive the shortcode roundtrip: they serialize to a JSON array, and
both the brackets and a bare `<` used to break the value out of the attribute,
dropping the condition while keeping the field required.
@kraftbj
kraftbj force-pushed the add/forms-conditional-logic-server branch from 3336b8a to 7d52857 Compare August 12, 2026 21:43
PHPCS treats the double-arrow misalignment as a warning, and this
repo's phpcs run exits non-zero on warnings, so it fails the build.

@kraftbj kraftbj left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed the server layer on its own. The architecture is right — one cached visibility map that validation and storage genuinely share, the flag checked at a single choke point, and the shortcode wire format is the most careful part of the PR. I traced [ -> &#91; -> esc_html with double_encode: false -> html_entity_decode(ENT_COMPAT) and it round-trips correctly for &, ", ,, \ and < inside rule values; JSON_HEX_AMP is what makes that safe, and esc_shortcode_val's backslash handling protects the JSON escapes from shortcode_parse_atts's stripcslashes. Also confirmed the round-1 enforcement gap is genuinely closed: only two paths reach storage and both now call $form->validate().

Two P1s though, both reachable through the editor UI with no forged input, and both cheaper to fix before the action signature and the wire format are in the field. Inline.

Two test notes worth pulling out, since they're the reason these survived: Feedback_Conditional_Logic_Test::test_storage_agrees_with_validation_about_a_cleared_prefilled_trigger asserts storage agrees with the form's own resolution rather than with what the browser rendered — so it currently pins the first P1 as correct behavior. And its scenario (a text field absent from $_POST) isn't reachable, since a cleared text input still posts an empty string. Rebuilt around a checkbox with default => 'true', that test becomes the regression test for it.

One behavior change to call out separately: the legacy path now also runs the "Please fill out at least one field." check and validate_ref(), neither gated on the flag. Almost certainly intended, but it changes what that path accepts on every site.

// default, then the logged-in user's details. Reading $_POST alone would make a
// prefilled form resolve against an empty one, so a field the visitor can already
// see satisfying a condition would render hidden and then flash into view.
$values[ $field_id ] = $field->get_computed_field_value(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The comment above is right for render and wrong for submit, and this function serves both.

get_computed_field_value() is POST -> GET -> default -> logged-in autofill. Every other reader of a submission is POST-only: has_value() at class-contact-form-field.php:336 and validate() at :384. So inside the single loop in Contact_Form::validate() the decision whether to validate a field comes from one value source and the validation itself from another.

Harmless for anything that always posts. It bites the controls that post nothing when unset — checkbox, explicit consent, radio, checkbox-multiple. No query string needed; the editor's own "Checked by default" toggle (field-checkbox/edit.jsx:46 sets defaultValue: 'true', mapped to default) is enough:

  1. subscribe is a checkbox, checked by default. details is required, shown when subscribe is_checked.
  2. Render: server and client agree, details visible.
  3. Visitor unchecks subscribe. Client value becomes '', details gets display: none.
  4. Submit. FormData omits the unchecked box entirely.
  5. Server: $_POST unset, $_GET unset, falls through to 'true' -> is_checked true -> details visible -> validated -> "Details is required" for a field that isn't on screen and can't be cleared.

Invert the rule and you get the other half: the visitor unchecks, fills in the now-visible details, and the server resolves it hidden, so without_hidden_answers() strips the answer with no error anywhere.

The $_GET half is narrower than it looks — the AJAX action is admin-ajax.php and the non-AJAX action is get_permalink(), so query args only survive for widget and block-template forms. The default fallback is the reliably reachable one.

apply_initial_field_visibility() should keep this chain, since the reasoning in the comment genuinely applies to render. get_resolved_field_visibility() should build values the way has_value() does — isset( $_POST[ $id ] ) ? wp_unslash( $_POST[ $id ] ) : ''. A $source argument covers both; that getter is only ever called from validation and storage, so it can be POST-only unconditionally.

// particular reads this payload directly for explicit consent and the subscriber's
// email, so a forged POST naming a hidden consent field could otherwise subscribe
// someone off a question that was never on screen.
$visible_fields = $this->fields;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This filter is defeated immediately — all three integrations recover the unfiltered set from $fields[0]->form:

  • service/class-post-to-url.php:159foreach ( $form->fields as $field ), so every hidden answer is POSTed to the configured webhook or Salesforce endpoint.
  • service/class-mailpoet-integration.php:177 (get_subscriber_data_from_fields) and :281 (the consent gate).
  • service/class-hostinger-reach-integration.php:137 and :180.

The v2 question resolves against this PR rather than in its favour: Feedback writes 'post_mime_type' => 'v3' (class-feedback.php:1598) while both integrations compute $is_v2_data = ( $post->post_mime_type === 'v2' ). So for every submission this code creates, the else branch is the live one — the branch that reads $form->fields and $consent_field->value instead of the Feedback API.

And hidden fields are posted: grunion.scss:1669 hides with display: none !important only, nothing disables or removes the inputs, and FormData includes them. So this is the ordinary path — fill a field, then change the trigger so it hides — not a forged request. The comment's own example lands: a hidden explicit-consent field ticked before it hid still passes has_consent(), and a hidden email field still supplies the subscriber address.

Everything else you filtered does hold — I checked comment_content, the consent flag, the subject, the author record, notification recipients, and Form_Webhooks, and they all read the $post_data that without_hidden_answers() already stripped. The leak is confined to these three $form->fields readers.

They only walk $fields to recover $form, so switching them to use the $fields argument they're already handed is mechanical. The alternative — unsetting hidden entries from $this->fields around the action — works too but is easier to get wrong.


$value = $this->get_field_value( $field_id, $post_data, $type );
$label = wp_strip_all_tags( $field->get_attribute( 'label' ) );
$key = $i . '_' . $label;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

$i now advances only for fields that get stored (the continue four lines up, ++$i at the bottom of the loop), where before it advanced for every renderable field.

For [Name, Extra(conditional), Message] one response persists 1_Name, 2_Extra, 3_Message and the next persists 1_Name, 2_Message — the same question on a different key depending on which siblings that visitor happened to see. The key is persisted into _feedback_all_fields in post_content and exposed over REST in the collection shape, so it's a stored identifier rather than a display detail.

Moving ++$i above the visibility continue fixes it — the counter is meant to encode position in the form, which is what makes it stable.

// the runtime hides.
$visibility_attrs = " data-jp-visibility-root='" . esc_attr( $id ) . "'"
. ( $this->has_conditional_logic() ? " data-jp-conditional='1'" : '' )
. ' data-wp-class--jetpack-field--conditionally-hidden="state.isFieldHidden"'

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

data-jp-conditional one line up is gated on has_conditional_logic(); these two directives aren't gated on anything — not the flag, not whether the field has logic, not whether the form has any. So every field of every form on every site running the package ships a class binding and a watch callback for a feature that's off by default, which contradicts the "adds nothing to the page" claim in the get_conditional_logic_context() docblock.

It's inert rather than wrong today — with the flag off the context is array(), resolveFormVisibility returns null, and both the getter and the callback early-return. But manageConditionalFocus is a data-wp-watch, so it re-runs on every context signal change on every field on sites that have nothing to do with this feature.

Wrapping the $visibility_attrs construction in Jetpack_Forms::is_conditional_logic_enabled() matches how every other new path here is gated. Worth noting Conditional_Logic_Initial_Render_Test::test_nothing_is_marked_when_the_feature_is_off only asserts on the hidden class, so it passes either way.

*
* @return Contact_Form
*/
private function parse_form( $trigger_value, $dependent_value ): Contact_Form {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This never reaches the defer it's testing. The parse-time gate at class-contact-form.php:2659 requires $_POST['action'] === 'grunion-contact-form', a matching contact-form-id, and a hash_equals match on contact-form-hash. parse_form sets only the two field values, so the whole if block — including the new $defer_to_full_form_validation decision at :2680 — is skipped.

test_the_parse_pass_defers_a_conditional_field and the first assertion of test_a_visible_required_field_is_only_caught_once_validate_runs therefore pass identically with the defer logic deleted. The branch has no coverage at all.

Which is a shame, because this file's header specifically says these tests exist "because the defer decision lives inside Contact_Form::parse_contact_field()" and that restating the decision "is how the missing legacy-path validation got through review" — the same shape of gap, one level further out. Setting the three $_POST keys in parse_form opens the gate.

Related coverage gap while you're in here: nothing exercises the production encode/decode chain end to end. parse_form hand-rolls the wire format rather than calling block_attributes_to_shortcode_attributes(), so esc_shortcode_val is never in the loop and the encoding can drift silently. One test running a rule value containing [, &, ", ,, \ and < through block_attributes_to_shortcode_attributes() -> parse_contact_field() -> do_shortcode() and asserting the decoded array equals the input would pin the most delicate code in the PR.

enejb added 3 commits August 13, 2026 08:01
The attribute kept its rules in a map keyed by condition kind, which cannot
express "any of these AND all of those" -- so supporting more than one grouping
later meant reshaping what is already stored. It is an array of groups now, each
combining its own rules with its own operator, combined with each other by the
top-level one.

Both evaluators handle several groups already, even though the V1 panel writes
exactly one: if only the storage changed, the second group would still arrive
needing an evaluator change. With a single group the outer reduction is a no-op,
so behaviour is unchanged.

Rules now carry their own type, so further condition kinds become new rule types
inside a group rather than another reshape. A rule of an unknown kind is
ignored, so a form saved by a newer editor degrades to its remaining conditions.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants