Add the current domain to new entities in every form mode
Backport of the 4.x MR to 3.0.x, for #3633250. The 4.x commits cherry-picked clean, plus the @group annotation the 3.0.x tests keep for Drupal 10. The test copies the node's default form class instead of naming Drupal\node\Form\NodeForm, which Drupal 10 does not have.
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_modeset up withsetFormClass()); - the
addoperation, which core'sDefaultHtmlRouteProvideruses for the add form of every entity type that declares anaddform 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 acustomform mode. A new node gets the active domain; an existing node keeps its domains.
Checked locally: the new-node test fails 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.)