Skip to content

Commit 9e6533b

Browse files
fix(console): a related tab's New keeps the parent it prefills when the child's relationship lookup declares dependsOn (#37283)
Fixes #37246 Clause-②: yes (widening) — one new export, `relatedCreateSeedOf`, on the published `@object-ui/plugin-detail/core` subpath; nothing is removed or renamed, and the package root exports the same names as before Metadata-protocol: none ## 维护者速读 - 用户能看到什么变化:在记录页的相关页签点「添加 → 新建」建子记录时,预填的父记录(如订单、商机)不再被藏在「请先选择客户」后面或被清空,客户字段一并带入,保存后子记录正确挂在父记录下。 - 为什么做:子对象的关系字段声明「依赖于客户」后,页签里新建会把预填的父记录藏在「请先选择客户」后面;若该字段还配了自动带出客户,打开表单时父记录会被清空,并且不报错地存成未关联的记录。这也挡住了 HotCRM 让「添加」只列同一客户记录的改动(HotCRM 那张 p1 卡)。 - 出错会怎样:只影响新建表单打开时带入的初始值;没有声明依赖的关系、父记录没有客户值时,行为与今天完全一样;可直接撤回本次改动。 - 要你做什么:无。 ## What changes A record page's related tab, **New** (the header's, or the one inside the **Add** picker), opened the child's create form with the parent link alone. When the child's relationship lookup declares `dependsOn` (a billing milestone's order `dependsOn` the milestone's account), the form drew the lookup gated ("Select Account first", the parent hidden); with a `lookupAutofill` that fills the account from the order, the opening fill wrote the account and the form's dependent-lookup clear then emptied the order, and Create saved the child with `crm_sales_order: null`, no error shown. Root cause: the New path seeded only the parent link (`formLink` = one `FIELD:ID` pair). The lookup's own **+ New** already seeds its `dependsOn` values (#35050) and the derived Add picker already scopes by them (#36729); the tab's New did neither. Fix (smallest change, one copy of the relation logic): - `ui/packages/plugin-detail/src/relatedParentScope.ts` (new, pure, exported on `/core` only, the subpath its one consumer imports): `dependsOnFromParent` is the `dependsOn` inversion `parentScopeOf` used to carry inline, moved here unchanged; `relatedCreateSeedOf(childFields, referenceField, parentRecord)` reads the same pairs as values. `RelatedList.tsx`'s `parentScopeOf` now calls `dependsOnFromParent`, so the picker scope and the New seed cannot drift. - `ui/packages/app-shell/src/views/RelatedRecordActionsBridge.tsx`: `onCreate` adds the seed to the link; `openChildForm` writes the parent pair first, then one `formLink` pair per seeded value (refresh-safe, like the link). A custom page's lists (`parentFromList`) name their own parents, which this bridge does not hold, so they keep the link alone. - `ui/packages/app-shell/src/console/AppContent.tsx`: the overlay reads every `formLink` pair (first pair of a field wins, a malformed pair is skipped) into the create's opening values. `urlParams.ts` documents the repeat. - `ui/apps/console/vite.config.ts`: the new module joins the `plugin-detail-core` chunk group, as that file requires for every module in the `/core` closure. Unblocks objectstack-ai/hotcrm#2753. Responsibility: - Whose code: the platform's own console related-record New path (`@object-ui/app-shell`, `@object-ui/plugin-detail`). - Existing platform path: the lookup's own **+ New** (#35050) and the Add picker (#36729) already handle `dependsOn`; the tab's New did not. - Who reaches it: every app whose child relationship lookup declares `dependsOn` (HotCRM: order to billing milestone, opportunity to contract). Files to read first (by risk): 1. `ui/packages/app-shell/src/console/AppContent.tsx`: the `formLinkValues` hunk (the URL contract every child create reads). 2. `ui/packages/app-shell/src/views/RelatedRecordActionsBridge.tsx`: the `onCreate` seed and `openChildForm` hunks. 3. `ui/packages/plugin-detail/src/relatedParentScope.ts`. Two-minute check: on a record whose related tab lists a child with a `dependsOn` relationship lookup, click Add, then New: the parent shows in its lookup (not "Select ... first"), the `dependsOn` field is filled, the URL carries two `formLink` pairs, and Create saves the parent id. ## Tests Pins, each a top-level `describe` for #37246 in the existing harness of the code it covers: - `RelatedRecordActionsBridge.createPredicates.test.tsx` (the bridge's "+ New" harness): New writes `formLink` = parent pair then `crm_account:acc-1`, with and without `lookupAutofill`; a `{ field, param }` entry and an expanded reference. Controls: no `dependsOn`, a parent with no account, a custom page's list: the link alone. - `AppContent.internalFormRetired-36425.test.tsx` (the record-form overlay harness, real `ModalForm`): billing milestone (with `lookupAutofill`) and contract (without): the relationship lookup is drawn ungated, the opening values hold both, Create posts the parent id and the account. Repeated-pair parse. Control: a lone parent link seeds the parent alone. - `RelatedList.derivedAddScope-36707.test.tsx` (the derived Add harness): `relatedCreateSeedOf` values and its empty cases. Control: the derived picker keeps its #36707 scope. <details><summary>Red on main, green after, ablation</summary> - Red, the three pins against main's code (the fix files reverted, pins at `5e0a09e127`): Test Files 3 failed, Tests 5 failed / 26 passed; e.g. `expected [ 'crm_sales_order:so-1' ] to deeply equal [ 'crm_sales_order:so-1', …(1) ]`. The reworked overlay pins against main's `AppContent.tsx`: 3 failed / 7 passed. - Green at `951db02b5d`: Test Files 3 passed, Tests 49 passed. - Ablation (`scripts/ablation-replace.mjs`, the bridge's `relatedCreateSeedOf(...)` call replaced by `undefined`; the test imports the bridge from source, so no `dist` leg): anchor 1 to 0, 3 failed / 19 passed (the three seed pins; the controls stayed green); restored, blob after restore == HEAD `672ca81d0086`, `git diff HEAD` empty. - Reproduction on main (readings, not committed): with main's URL, the overlay drew `lookup-trigger-gated` "Select Account first" for both children. At the form level, `dependsOn: ['account']` plus a `lookupAutofill` filling `account`, opened with the parent alone: account filled, the relationship lookup back to "Select…", submit posted the relationship as `null`. Opened with the seeded account: the relationship kept its record and the autofill still filled its other targets. </details> ## Acceptance notes - The overlay harness serves its lookups no record read, so it pins the gate and the saved payload, not the label text; the label and the autofill interplay were read at the form level (above). - The form's dependent-lookup clear treats the opening `lookupAutofill` fill as an edit of the field it writes, which is what emptied the order in case 1. The seed sets that field before the form opens, so one level down nothing moves. It does not hold one level further: if the seeded `dependsOn` field is itself a lookup with a `dependsOn` and a `lookupAutofill` of its own (account `dependsOn` region, filled from the account), the opening fill writes region, the clear empties account, and the emptied account empties the order. The child then saves unlinked, which main does too. That transitive value cannot be read off the parent record, so the fix belongs in the form's clear, not in this seed: tracked as #37289. A create opened another way, with a relationship value and an empty `dependsOn` field (a URL prefill), meets the same clear. - `ObjectDataPage`'s New from a record trail (the "View all" list) writes `formLink` with the parent pair alone, so a `dependsOn` relationship lookup there meets the same gate. Not changed here: tracked as #37290. ## Verification <details><summary>Local suites and type-check at 47db09e (origin/main 1b91538 merged in)</summary> - `pnpm --dir ui exec vitest run --maxWorkers=2 packages/plugin-detail/`: Test Files 418 passed, 1 skipped; Tests 3954 passed, 18 skipped; exit 0. - `pnpm --dir ui exec vitest run --maxWorkers=2 packages/app-shell/`: Test Files 2438 passed, 1 skipped; Tests 23194 passed, 9 skipped; exit 0. - `pnpm --filter @object-ui/plugin-detail type-check`: exit 0. `pnpm --filter @object-ui/app-shell type-check`: exit 0, after rebuilding `@object-ui/plugin-detail` (its `/core` types are read from `dist`). - `pnpm check:new-line-citations` (ui): 0 new citations, exit 0. </details> <details><summary>Derived gate families (`dispatch-gates.mjs --commands`, the same list at cbee57c and 47db09e)</summary> - Exit 0 at cbee57c (the fix commit, before the main merge): every listed family except the two below. The re-run on 47db09e is cited in the report comment on #37246. - NOT MEASURED: `pnpm check:dual-build-cjs-loads`, reason: PREREQUISITE NOT MET (exit 3), no `dist/` for packages this diff does not touch (needs a full `pnpm build`). CI carries it. - NOT MEASURED at cbee57c: `pnpm check:type-check-debt`, reason: its re-measure queued behind the shared verify lock past its budget (exit 3). The final-head re-run is in the report comment. - `pnpm --dir ui exec vitest run scripts/`: in the report comment (queued on the shared lock while this PR opened). - Repo-wide `pnpm lint` and the full farm: CI. </details> <details><summary>Rework round at 8afea3b (L1 REWORK: M1, S1, S2, N2; main not merged)</summary> - M1: the package-root re-export of `relatedCreateSeedOf` is dropped (`src/index.tsx`); the `/core` export stays. `core.ts`'s header no longer says every `/core` name is also on the root. The changeset declares `Clause-②: yes (widening)`; the level stays `patch`, and `Metadata-protocol: none` stays. - N2: a new pin in `RelatedList.derivedAddScope-36707.test.tsx` covers a two-entry `dependsOn`. When the parent answers both entries, both fields are seeded. When it answers only one, neither is seeded, and the derived picker offers none either. - Pins plus `pluginCoreSubpaths-33581.test.ts`: Test Files 4 passed, Tests 53 passed. - `pnpm --filter @object-ui/plugin-detail type-check`: exit 0. `pnpm --filter @object-ui/app-shell type-check`: exit 0, after rebuilding plugin-detail's `dist`. - Derived families: the same 46 as before. 44 exit 0, `check:type-check-debt` included. `--ran` reports 45 run and 1 NOT MEASURED. NOT MEASURED: `check:dual-build-cjs-loads` (needs a full build, exit 3) and `pnpm --dir ui exec vitest run scripts/` (lock timeout, exit 99). CI carries both. - CI at 8afea3b: the 12 required check-runs are `success` (47 success, 11 skipped). </details> --- _Generated by [Claude Code](https://claude.ai/code/session_01QSeKYmRepQK9DkZeU7F53D)_ <!-- signed: repo:objectstack#4 · os-justin · session_01QSeKYmRepQK9DkZeU7F53D --> --------- Co-authored-by: Claude <noreply@anthropic.com> Co-authored-by: objectstack-fleet[bot] <332303061+objectstack-fleet[bot]@users.noreply.github.com>
1 parent 1a62867 commit 9e6533b

11 files changed

Lines changed: 402 additions & 48 deletions
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
---
2+
'@object-ui/app-shell': patch
3+
'@object-ui/plugin-detail': patch
4+
'@object-ui/console': patch
5+
---
6+
7+
fix(console): a related tab's New keeps the parent it prefills when the child's relationship lookup declares `dependsOn`
8+
9+
Clause-②: yes (widening) — one new export, `relatedCreateSeedOf`, on the published `@object-ui/plugin-detail/core` subpath; nothing is removed or renamed, and the package root exports the same names as before
10+
Metadata-protocol: none
11+
12+
On a record page's related tab, New (the header's, or the one inside the Add picker) opened the child's create form with the parent linked and nothing else. When the child's relationship lookup declares `dependsOn` (a billing milestone's order `dependsOn` the milestone's account), the form drew that lookup gated ("Select Account first") with the parent hidden, or, with a `lookupAutofill` that fills the account from the order, filled the account and then emptied the order, and Create saved the child without its parent and without an error.
13+
14+
The New now opens with each `dependsOn` field of the relationship lookup seeded from the parent record — the child's field takes the parent's value, the same pairs the derived Add picker scopes its candidates by. The parent stays visible and is saved. A `dependsOn` field that is itself a lookup with a `dependsOn` and a `lookupAutofill` of its own can still be emptied by the form's dependent-lookup clear when the form opens; that clear is tracked separately. A relationship lookup without `dependsOn`, or a parent with no value for it, opens with the parent link alone, as before; the Add picker's scope is unchanged.
15+
16+
- The record-form overlay's `formLink` URL parameter repeats: the parent pair first, then one `field:value` pair per seeded value, so a refresh reopens the form with all of them.
17+
- `@object-ui/plugin-detail/core` exports `relatedCreateSeedOf(childFields, referenceField, parentRecord)`, the values a related New opens with beside the parent link.
18+
- A custom page's related lists, which each bind a parent of their own, still open New with the parent link alone.

‎ui/apps/console/vite.config.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1577,7 +1577,7 @@ export default defineConfig({
15771577
},
15781578
{
15791579
name: 'plugin-detail-core',
1580-
test: /[\\/]packages[\\/]plugin-detail[\\/]src[\\/](core|autoLayout|relatedListCompact|relatedListSort|queueClaim|ConcurrentUpdateDialog|useDetailTranslation|recordFieldAccess|useRecordEditable|useRelatedCounts|renderers[\\/]recordActivityFeed|synth[\\/](relatedListEntry|relatedArrangement|buildDefaultPageSchema))\.tsx?$/,
1580+
test: /[\\/]packages[\\/]plugin-detail[\\/]src[\\/](core|autoLayout|relatedListCompact|relatedListSort|relatedParentScope|queueClaim|ConcurrentUpdateDialog|useDetailTranslation|recordFieldAccess|useRecordEditable|useRelatedCounts|renderers[\\/]recordActivityFeed|synth[\\/](relatedListEntry|relatedArrangement|buildDefaultPageSchema))\.tsx?$/,
15811581
priority: 71,
15821582
includeDependenciesRecursively: false,
15831583
},

‎ui/packages/app-shell/src/console/AppContent.tsx‎

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -861,17 +861,25 @@ export function AppContent({ extraRoutes, extraRoutesNoApp }: AppContentProps =
861861
// the URL means Back closes the overlay and a refresh reopens it still
862862
// correctly parent-linked — no transient component state to lose.
863863
const formObjectParam = searchParams.get(RECORD_FORM_OBJECT_PARAM);
864-
const formLinkParam = searchParams.get(RECORD_FORM_LINK_PARAM);
864+
// objectstack#37246 — `formLink` repeats: the parent pair first, then the
865+
// values it seeds beside it (the relationship lookup's `dependsOn` fields).
866+
// Keyed on the pairs' JSON text, a primitive, so the values keep their identity
867+
// while the URL does (AGENTS.md #10).
868+
const formLinkKey = JSON.stringify(searchParams.getAll(RECORD_FORM_LINK_PARAM));
865869
const editingRecord = useMemo(
866870
() => (recordFormParam && recordFormParam !== 'new' ? { id: recordFormParam } : null),
867871
[recordFormParam],
868872
);
869873
const formLinkValues = useMemo(() => {
870-
if (!formLinkParam) return undefined;
871-
const i = formLinkParam.indexOf(':');
872-
if (i <= 0) return undefined;
873-
return { [formLinkParam.slice(0, i)]: formLinkParam.slice(i + 1) };
874-
}, [formLinkParam]);
874+
const values: Record<string, string> = {};
875+
for (const pair of JSON.parse(formLinkKey) as string[]) {
876+
const i = pair.indexOf(':');
877+
const field = pair.slice(0, i);
878+
if (i <= 0 || field in values) continue;
879+
values[field] = pair.slice(i + 1);
880+
}
881+
return Object.keys(values).length > 0 ? values : undefined;
882+
}, [formLinkKey]);
875883
const [refreshKey, setRefreshKey] = useState(0);
876884

877885
const isDialogOpen = !!recordFormParam;

‎ui/packages/app-shell/src/console/__tests__/AppContent.internalFormRetired-36425.test.tsx‎

Lines changed: 88 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@
2222
import '@testing-library/jest-dom/vitest';
2323
import { describe, it, expect, vi, beforeEach, afterEach, afterAll } from 'vitest';
2424
import React from 'react';
25-
import { render, cleanup, waitFor, screen, within } from '@testing-library/react';
25+
import { render, cleanup, waitFor, screen, within, fireEvent } from '@testing-library/react';
2626
import { MemoryRouter, Routes, Route } from 'react-router-dom';
2727
import { registerAllFields } from '@object-ui/fields';
2828

@@ -112,7 +112,35 @@ const AUTHORED = {
112112
},
113113
};
114114
const PLAIN = { name: 'crm_note', label: 'Note', fields: FIELDS, fieldGroups: FIELD_GROUPS };
115-
const OBJECTS = [AUTHORED, PLAIN];
115+
116+
// objectstack#37246 — a child whose relationship lookup is scoped by the
117+
// child's own account (`dependsOn`), with and without a `lookupAutofill` that
118+
// fills that account from the parent.
119+
const MILESTONE = {
120+
name: 'crm_billing_milestone',
121+
label: 'Billing Milestone',
122+
fields: {
123+
name: { type: 'text', label: 'Name' },
124+
crm_sales_order: {
125+
type: 'lookup',
126+
reference: 'crm_sales_order',
127+
label: 'Order',
128+
dependsOn: ['crm_account'],
129+
lookupAutofill: [{ target: 'crm_account', source: 'crm_account' }],
130+
},
131+
crm_account: { type: 'lookup', reference: 'crm_account', label: 'Account' },
132+
},
133+
};
134+
const CONTRACT = {
135+
name: 'crm_contract',
136+
label: 'Contract',
137+
fields: {
138+
name: { type: 'text', label: 'Name' },
139+
crm_account: { type: 'lookup', reference: 'crm_account', label: 'Account' },
140+
crm_opportunity: { type: 'lookup', reference: 'crm_opportunity', label: 'Related Opportunity', dependsOn: ['crm_account'] },
141+
},
142+
};
143+
const OBJECTS = [AUTHORED, PLAIN, MILESTONE, CONTRACT];
116144

117145
const dataSourceStub = {
118146
onConnectionStateChange: () => () => {},
@@ -239,3 +267,61 @@ describe('#36425 — the New / Edit dialog reads no internal form view', () => {
239267
expect(a.fields).toEqual(b.fields);
240268
});
241269
});
270+
271+
/**
272+
* objectstack#37246 — a related tab's New on a child whose relationship
273+
* lookup declares `dependsOn` (a milestone's order `dependsOn` its account): the
274+
* pre-link carries the parent AND each `dependsOn` value the parent answers, as
275+
* repeated `formLink` pairs (`RelatedRecordActionsBridge`). The dialog opens
276+
* with all of them, so the lookup holds its parent in the open instead of
277+
* behind 「Select Account first」, and Create saves the parent.
278+
*/
279+
describe('#37246 — a related New pre-links the parent with its dependsOn values', () => {
280+
/**
281+
* The relationship lookup draws its own trigger, holding the parent, and no
282+
* gate: a lookup whose `dependsOn` field is empty draws `lookup-trigger-gated`
283+
* (「Select Account first」) and hides the value it holds. This harness serves
284+
* the lookups no record read, so their labels are not drawn here.
285+
*/
286+
async function createFrom(url: string, child: string, relationship: string) {
287+
probe.realModal = true;
288+
const schema = await openAt(url, child);
289+
const dialog = await screen.findByRole('dialog', undefined, { timeout: 5000 });
290+
await waitFor(() => expect(within(dialog).getByTestId(`lookup-trigger-${relationship}`)).toBeInTheDocument(), { timeout: 5000 });
291+
expect(within(dialog).queryByTestId('lookup-trigger-gated')).toBeNull();
292+
fireEvent.click(within(dialog).getByRole('button', { name: 'Create' }));
293+
await waitFor(() => expect(dataSourceStub.create).toHaveBeenCalled(), { timeout: 5000 });
294+
expect(dataSourceStub.create.mock.calls[0][0]).toBe(child);
295+
return { schema, saved: dataSourceStub.create.mock.calls[0][1] };
296+
}
297+
298+
it('with a lookupAutofill on the relationship: the order is drawn ungated, and Create saves it with its account', async () => {
299+
const { schema, saved } = await createFrom(
300+
'/apps/crm/crm_sales_order?form=new&formObject=crm_billing_milestone&formLink=crm_sales_order:so-1&formLink=crm_account:acc-1',
301+
'crm_billing_milestone',
302+
'crm_sales_order',
303+
);
304+
expect(schema.initialValues).toStrictEqual({ crm_sales_order: 'so-1', crm_account: 'acc-1' });
305+
expect(saved).toMatchObject({ crm_sales_order: 'so-1', crm_account: 'acc-1' });
306+
});
307+
308+
it('with no lookupAutofill: the opportunity is drawn, never 「Select Account first」, and Create saves it', async () => {
309+
const { schema, saved } = await createFrom(
310+
'/apps/crm/crm_opportunity?form=new&formObject=crm_contract&formLink=crm_opportunity:opp-1&formLink=crm_account:acc-1',
311+
'crm_contract',
312+
'crm_opportunity',
313+
);
314+
expect(schema.initialValues).toStrictEqual({ crm_opportunity: 'opp-1', crm_account: 'acc-1' });
315+
expect(saved).toMatchObject({ crm_opportunity: 'opp-1', crm_account: 'acc-1' });
316+
});
317+
318+
it('control: a lone parent pre-link still seeds just the parent', async () => {
319+
const schema = await openAt('/apps/crm/crm_note?form=new&formObject=crm_case&formLink=account:acct-parent', 'crm_case');
320+
expect(schema.initialValues).toStrictEqual({ account: 'acct-parent' });
321+
});
322+
323+
it('the first pair of a field wins, and a malformed pair is skipped', async () => {
324+
const schema = await openAt('/apps/crm/crm_note?form=new&formObject=crm_case&formLink=account:acct-parent&formLink=account:other&formLink=:x&formLink=status:open', 'crm_case');
325+
expect(schema.initialValues).toStrictEqual({ account: 'acct-parent', status: 'open' });
326+
});
327+
});

‎ui/packages/app-shell/src/urlParams.ts‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,10 @@ import { STUDIO_RETURN_PARAM } from './views/studio-design/studioAddress.js';
4646
* | | framework#2604 D3). | |
4747
* | `formLink` | `"<fkField>:<parentId>"` — create-mode parent | |
4848
* | | pre-link for a child task; refresh-safe. | with `form` |
49+
* | | Repeats: further `"<field>:<value>"` pairs are | |
50+
* | | values seeded beside the parent (the relation- | |
51+
* | | ship lookup's `dependsOn` fields, | |
52+
* | | objectstack#37246). | |
4953
* | `tab` | Active record-detail tab (stable semantic | replace |
5054
* | | values: `details` / `related:<child>` / | |
5155
* | | `related` / `activity` / `history`, | |
@@ -111,7 +115,10 @@ export const RECORD_FORM_PARAM = 'form';
111115
/** Child-task object override for the record-form overlay (objectstack-ai/objectstack#2604 D3). */
112116
export const RECORD_FORM_OBJECT_PARAM = 'formObject';
113117

114-
/** Child-task parent pre-link `"<fkField>:<parentId>"` (objectstack-ai/objectstack#2604 D3). */
118+
/**
119+
* Child-task parent pre-link `"<fkField>:<parentId>"` (objectstack-ai/objectstack#2604 D3),
120+
* repeated for each value seeded beside it (objectstack#37246).
121+
*/
115122
export const RECORD_FORM_LINK_PARAM = 'formLink';
116123

117124
/** Active record-detail tab (objectui#2257; stable semantic values). */

‎ui/packages/app-shell/src/views/RelatedRecordActionsBridge.tsx‎

Lines changed: 27 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,7 @@ import {
9595
import { evalRowPredicate, isMultiValueRelationship, resolveAffordance, type ActionDef, type RowCrudPredicates } from '@object-ui/core';
9696
import { actionRendersAt, type ActionLocation } from '@object-ui/types';
9797
import { usePermissions } from '@object-ui/permissions';
98+
import { relatedCreateSeedOf } from '@object-ui/plugin-detail/core';
9899
import { servesRecordRead, type RecordReadPrincipal } from '../utils/recordReadServed.js';
99100
import { RECORD_FORM_PARAM, RECORD_FORM_OBJECT_PARAM, RECORD_FORM_LINK_PARAM, RECORD_TRAIL_PARAM, appendRecordTrail } from '../urlParams.js';
100101
import { documentHref } from './documentHref.js';
@@ -460,7 +461,11 @@ export function RelatedRecordActionsBridge({
460461
// object that is the full-page create route `AppContent`'s `handleEdit`
461462
// navigates to (`resolveRecordFormTarget`), not the overlay.
462463
const openChildForm = useCallback(
463-
(opts: { objectName: string; recordId?: string; link?: { field: string; parentId: string | number } }) => {
464+
(opts: {
465+
objectName: string;
466+
recordId?: string;
467+
link?: { field: string; parentId: string | number; seed?: Record<string, string> };
468+
}) => {
464469
if (opts.recordId == null && !opts.link) {
465470
const target = resolveRecordFormTarget({
466471
objectDef: objects.find((o: any) => o?.name === opts.objectName),
@@ -475,8 +480,16 @@ export function RelatedRecordActionsBridge({
475480
const sp = new URLSearchParams(window.location.search);
476481
sp.set(RECORD_FORM_PARAM, opts.recordId ?? 'new');
477482
sp.set(RECORD_FORM_OBJECT_PARAM, opts.objectName);
478-
if (opts.link) sp.set(RECORD_FORM_LINK_PARAM, `${opts.link.field}:${opts.link.parentId}`);
479-
else sp.delete(RECORD_FORM_LINK_PARAM);
483+
sp.delete(RECORD_FORM_LINK_PARAM);
484+
if (opts.link) {
485+
// The parent link first, then the values it seeds beside it
486+
// (objectstack#37246): one `formLink` pair each, all in the URL so a
487+
// refresh reopens the form with them.
488+
sp.append(RECORD_FORM_LINK_PARAM, `${opts.link.field}:${opts.link.parentId}`);
489+
for (const [field, value] of Object.entries(opts.link.seed ?? {})) {
490+
sp.append(RECORD_FORM_LINK_PARAM, `${field}:${value}`);
491+
}
492+
}
480493
setSearchParams(sp); // push → Back closes the overlay
481494
},
482495
[setSearchParams, objects, base, navigate],
@@ -666,10 +679,20 @@ export function RelatedRecordActionsBridge({
666679
handlers.onCreate = () => {
667680
const canLink =
668681
relationshipField && parentId != null && parentId !== '';
682+
// objectstack#37246 — a relationship lookup scoped by the child's
683+
// own fields (`dependsOn`) opens with them seeded from the parent,
684+
// or the form gates the lookup (「Select Account first」) and its
685+
// `lookupAutofill` empties it: the child saved without its parent.
686+
// The parent record is this mount's own; a custom page's lists
687+
// each name a parent of their own (`parentFromList`), which this
688+
// bridge does not hold, so they seed the link alone.
689+
const seed = canLink && !parentFromList && parentRecord
690+
? relatedCreateSeedOf(childDef.fields, relationshipField as string, parentRecord)
691+
: undefined;
669692
openChildForm({
670693
objectName,
671694
link: canLink
672-
? { field: relationshipField as string, parentId: parentId as string | number }
695+
? { field: relationshipField as string, parentId: parentId as string | number, seed }
673696
: undefined,
674697
});
675698
};

0 commit comments

Comments
 (0)