Skip to content

RelationController behavior: support for deeply nested relations - #1499

Draft
mjauvin wants to merge 8 commits into
developfrom
nested-relation-controller
Draft

RelationController behavior: support for deeply nested relations#1499
mjauvin wants to merge 8 commits into
developfrom
nested-relation-controller

Conversation

@mjauvin

@mjauvin mjauvin commented Jul 6, 2026

Copy link
Copy Markdown
Member

We can now use this in config_relation.yaml:

items:
    label: Items
    view:
        toolbarButtons: create|delete
        list: $/acme/nested/models/item/columns.yaml
    manage:
        form: $/acme/nested/models/item/fields.yaml

items[taxes]:
    label: taxes
    view:
        toolbarButtons: create|delete
        list: $/acme/nested/models/tax/columns.yaml
    manage:
        form: $/acme/nested/models/tax/fields.yaml

Which would create a popup to manage Items in an Order, along with another nested popup to manage Taxes within that Items popup (see screenshot):

Note: deeper nesting can be achieved as well (e.g. items[taxes][other])

image

The nested popups now have an offset which makes it easier to see the nesting.

Summary by CodeRabbit

Summary

  • New Features

    • Nested relation fields specified with bracket paths (multi-level/repeated) are supported more reliably.
    • Multiple simultaneously open popups now cascade with a small visual offset to reduce overlap.
  • Bug Fixes

    • Relation actions (create/update/remove/unlink/delete) now target the correct nested record and stay isolated from stale request context.
    • Popup callbacks consistently report the intended relation field name, improving nested UI routing and preventing DOM/session collisions.
  • Tests

    • Added a comprehensive nested relation controller test suite covering recursive, ambient, and regression scenarios.

@mjauvin mjauvin added this to the 1.2.13 milestone Jul 6, 2026
@mjauvin mjauvin self-assigned this Jul 6, 2026
@mjauvin mjauvin added enhancement PRs that implement a new feature or substantial change needs review Issues/PRs that require a review from a maintainer labels Jul 6, 2026
@coderabbitai

coderabbitai Bot commented Jul 6, 2026

Copy link
Copy Markdown

Review Change Stack

Important

Draft PR not reviewed

Draft PRs are not automatically reviewed by default.

  • Trigger a manual review

To automatically review draft PRs, update your CodeRabbit configuration:

reviews:
  auto_review:
    drafts: true

Walkthrough

This PR extends RelationController for bracketed nested relation fields, including nested context resolution, config aliasing, ambient stack handling, session-key caching, and nested manage-mode selection. RelationManager now initializes relation context during render. Relation button partials now use the leaf field name for client-side change events. A new test suite covers nested, recursive, and regression cases. Popup display now offsets stacked dialogs.

File(s) Summary
modules/backend/behaviors/RelationController.php Adds nested relation field state, bracket path parsing, hop-based model resolution, config aliasing, ambient nesting stack, scoped id/session key handling, and manage mode resolution.
modules/backend/behaviors/relationcontroller/partials/_button_delete.php, _button_remove.php, _button_unlink.php Switch JS change-event field references from relationField to relationFieldName.
modules/backend/formwidgets/RelationManager.php Explicitly calls initRelation() before rendering.
modules/backend/tests/behaviors/RelationControllerNestedTest.php New test suite with fixture models and nested relation behavior coverage.
modules/system/assets/ui/js/popup.js, modules/system/assets/ui/storm-min.js Adds Popup.STACK_OFFSET and cascading offset logic for stacked popups.

Estimated code review effort: 4 (Complex) | ~75 minutes

Sequence Diagram(s)

sequenceDiagram
  participant RelationController
  participant resolveNestedContext
  participant resolveModelForHops
  participant aliasNestedConfig
  RelationController->>resolveNestedContext: initRelation(model, field)
  resolveNestedContext->>resolveModelForHops: walk bracket hops
  resolveModelForHops-->>resolveNestedContext: resolved leaf model
  RelationController->>aliasNestedConfig: map nested config key
  aliasNestedConfig-->>RelationController: aliased config
Loading

Related issues: None specified.

Related PRs: None specified.

Suggested labels: backend, javascript, tests, enhancement

Suggested reviewers: Winter CMS backend maintainers familiar with RelationController and relation form widgets.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main change: RelationController now supports deeply nested relations.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch nested-relation-controller

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@mjauvin
mjauvin requested review from LukeTowers, damsfx and jaxwilko July 6, 2026 13:15

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Nitpick comments (1)
modules/system/assets/ui/js/popup.js (1)

319-319: 🎯 Functional Correctness | 🔵 Trivial | 💤 Low value

Global selector counts unrelated, non-nested popups.

$('.control-popup.in') counts every currently open popup document-wide, not just ancestors of the popup being shown. Two unrelated popups opened independently (not nested within each other) would still cascade-offset each other. This may be acceptable for the feature's intended nested-relation use case, but worth confirming it matches the desired UX for unrelated simultaneous popups.

Also applies to: 331-331

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@modules/system/assets/ui/js/popup.js` at line 319, The popup stacking logic
in popup.js is using a document-wide selector to compute stack depth, so
unrelated open popups are being counted as if they were nested. Update the logic
around the stackDepth calculation and the related offset behavior to count only
ancestor popups for the popup being shown, using the relevant popup
show/positioning code paths instead of a global $('.control-popup.in') match.
Verify the same fix is applied to the companion stack-depth usage at the other
occurrence so simultaneous independent popups do not cascade-offset each other.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@modules/backend/behaviors/RelationController.php`:
- Around line 654-677: The nested hop lookup in resolveModelForHops is bypassing
the current parent relation scope by querying the related model directly, which
can resolve records outside the intended chain. Update the lookup inside
resolveModelForHops to use the relation instance from $model->{$relationName}()
when finding the hop by id, so each hop remains constrained to its parent
relation; keep the existing relation validation and fallback to a new instance
for non-numeric ids.
- Around line 679-725: Avoid mutating $this->originalConfig in
RelationController::aliasNestedConfig(), since the nested alias can leak into
later initRelation() calls and collide with a real root-level field. Update the
aliasing logic to write the leaf-name entry onto the cloned $this->config used
by getConfig()/makeConfig(), while leaving $this->originalConfig unchanged; keep
the existing config key checks and exception paths intact.

In `@modules/system/assets/ui/js/popup.js`:
- Around line 330-336: The Popup positioning logic in the show/reload flow
leaves stale inline offsets on reused dialogs because `top` and `left` are only
applied when `stackDepth > 0`. Update the offset handling in `Popup` so that
when a popup is shown with `stackDepth === 0`, any previously set `top`/`left`
styles are cleared before centering, ensuring reused instances from `$.fn.popup`
and `data.reload()` do not keep an old stacked position.

---

Nitpick comments:
In `@modules/system/assets/ui/js/popup.js`:
- Line 319: The popup stacking logic in popup.js is using a document-wide
selector to compute stack depth, so unrelated open popups are being counted as
if they were nested. Update the logic around the stackDepth calculation and the
related offset behavior to count only ancestor popups for the popup being shown,
using the relevant popup show/positioning code paths instead of a global
$('.control-popup.in') match. Verify the same fix is applied to the companion
stack-depth usage at the other occurrence so simultaneous independent popups do
not cascade-offset each other.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 03a5e5e1-f7e1-4bad-95f8-316be00b1c43

📥 Commits

Reviewing files that changed from the base of the PR and between 8a43ba2 and 3a13b74.

📒 Files selected for processing (7)
  • modules/backend/behaviors/RelationController.php
  • modules/backend/behaviors/relationcontroller/partials/_button_delete.php
  • modules/backend/behaviors/relationcontroller/partials/_button_remove.php
  • modules/backend/behaviors/relationcontroller/partials/_button_unlink.php
  • modules/backend/formwidgets/RelationManager.php
  • modules/backend/tests/behaviors/RelationControllerNestedTest.php
  • modules/system/assets/ui/js/popup.js

Comment thread modules/backend/behaviors/RelationController.php
Comment thread modules/backend/behaviors/RelationController.php
Comment thread modules/system/assets/ui/js/popup.js Outdated
@mjauvin mjauvin changed the title RelationController behavior support for deeply nested relations RelationController behavior: support for deeply nested relations Jul 6, 2026
@mjauvin
mjauvin marked this pull request as draft July 25, 2026 21:54
@LukeTowers LukeTowers modified the milestones: 1.2.13, 1.3.0 Aug 6, 2026
@AIC-BV

AIC-BV commented Aug 26, 2026

Copy link
Copy Markdown
Contributor

AI dump, hopefuly this makes any sense to you

Tested this branch against a real three-level config in our own backend (Order → closets → paslatten → closet). Two levels work well — correct parent scoping, sibling isolation, DOM/session isolation via the hashed alias, and the popup offset all behaved. Three levels hit one bug.

Symptom

A form yaml rendered as a nested manage form, whose own partial calls relationRender('closet'), throws:

BadMethodCallException: Call to undefined method Aic\Account\Models\Closet::closet()

#6 RelationController.php(450): Model->__call('closet', Array)
#7 RelationController.php(304): RelationController->initRelation(Object(Closet), 'closet')
#8 RelationController.php(931): RelationController->validateField('closet')
#9 RelationController->relationRender('closet')

closet is a relation on Paslatten, not on Closet — the leaf resolved against the grandparent.

Cause

The ambient branch in resolveNestedContext() trusts $model, per its docblock ("it's the widget's own bound model"). But the call arrives as relationRender() → validateField() → initRelation($this->model), and $this->model is the record of the enclosing relation. At one level of nesting that is the parent, so it works; at two it is the grandparent.

Patch

 if ($ambientPath !== null) {
     $this->nestedField = $ambientPath . '[' . $field . ']';
-    return [$model, $field, true];
+    [$hops] = $this->parseBracketField($this->nestedField);
+
+    return [$this->resolveModelForHops($this->rootModel, $hops), $field, true];
 }

This is what the reconstructed branch two lines below already does, so both cases share one resolution mechanism and the ambient path keeps resolveModelForHops()'s $relation->find($id) parent check at every depth.

All 22 existing tests still pass unmodified — depth 2 resolves to the same model either way, which is also why the suite doesn't currently catch this. I added testAmbientFieldTwoLevelsDeepResolvesInnermostAncestorNotEnclosingRecord using your self-referencing Item → items → Item fixture; it fails without the patch (resolves Item A instead of the sub-item) and passes with it. Full backend suite diffed both ways shows no other change.

After the patch, three levels resolve correctly in the browser: closet A's paslat renders closet A, closet B's renders closet B.

Happy to open this as a PR against nested-relation-controller if useful.

Two smaller notes:

  1. The branch is diverged rather than just ahead (12 commits behind develop on backend, 7 on system), so installing it removes the FieldSet formwidget, the Twig SecurityPolicy hardening and a few tests. Worth merging develop to make it testable against a current tree.
  2. aliasNestedConfig() throws a hard ApplicationException when a nested path has no config entry. That means any shared form yaml calling relationRender() breaks the popup unless every host controller re-declares the whole chain. Declaring it is reasonable, but the failure mode is harsh — left alone here since it looks like a design call for you.

resolveNestedContext()'s ambient branch trusted the model handed to
initRelation() as the relation's parent. That model is $this->model,
set from the ENCLOSING relation, because the call arrives as
relationRender() -> validateField() -> initRelation($this->model).

At one level of nesting the enclosing record is the parent, so this
works. At two it is the grandparent, and the leaf relation resolves
against the wrong model - in practice a BadMethodCallException, since
the grandparent's class usually has no such relation.

Walk the ambient path's hops from the root instead, exactly as the
reconstructed branch below already does. Both cases now share one
resolution mechanism, and the ambient path gains resolveModelForHops()'s
$relation->find($id) parent check at every depth.

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement PRs that implement a new feature or substantial change needs review Issues/PRs that require a review from a maintainer

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants