Add the current domain to new entities in every form mode

Backport of !503 (merged) (4.x) to 2.0.x, for #3633250. On 2.0.x the hook is domain_access_entity_prepare_form() in domain_access.module, and the check was $operation === 'default' only: the register fix of #3564574 never reached 2.0.x, so this also makes "Add current domain" work on the user registration form here. The test sets no active domain: 2.0.x's negotiator negotiates it again from the request host, so the test expects the negotiated one. It adds a third case, a new user on the registration form, and copies the node's default form class because Drupal 10 has no Drupal\node\Form\NodeForm.

On 4.x, 3.x and 3.0.x, DomainAccessEntityHooks::entityPrepareForm() added the current domain to a new entity only when the form operation was default or register. Any other operation skipped it:

  • a custom form mode, as in the issue (for example custom_form_mode set up with setFormClass());
  • the add operation, which core's DefaultHtmlRouteProvider uses for the add form of every entity type that declares an add form handler, such as Media and Block content;
  • the operations contrib modules use when they build entity forms themselves.

The check came with the first patch of #2909853, when the old field default_value_callback was moved to hook_entity_prepare_form. That callback ran for every new entity, whatever the form, and nothing in that issue explains the narrower list. #3564574 later added register for one reported case.

  • Fix: drop the operation condition. $entity->isNew() already keeps edit and delete forms out, and the setting's description in the docs already says "new entities".
  • Kernel test DomainAccessFormModeDefaultValueTest: builds the node form through a custom form mode. A new node gets the active domain; an existing node keeps its domains. On 2.0.x, a new user on the registration form gets the active domain too.

Checked locally: the new-node and new-user tests fail without the fix, and the existing-node test fails when the isNew() check is removed. phpcs and cspell are clean on the changed files; phpstan reports nothing new.

Behavior note: with "Add current domain to default values" on, new entities now get the current domain in every entity form, not only on the default and register forms. As on the default form before, hiding the field in a form display does not stop this: the domain is added to the entity and saved. A site that wants no current domain in one form mode can turn the setting off for that bundle, or reset the field in its own hook_entity_prepare_form(). No cost change: one in_array() less.

AI-Generated: Yes (Claude Code was used to help write the backport, its test and this description. I reviewed them, and the new tests were confirmed to fail without the change and to pass with it.)

Merge request reports

Loading
Loading