Skip to content
16 changes: 16 additions & 0 deletions .changeset/36865-lookup-param-allowcreate-filters.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
---
'@object-ui/core': patch
'@object-ui/fields': patch
'@object-ui/plugin-grid': patch
'@object-ui/i18n': patch
'@object-ui/app-shell': patch
---

fix(fields): an action's lookup param honours the borrowed field's `allowCreate: false`, and a record created in a filtered picker that fails the filters is not selected

Clause-②: yes (widening)
Metadata-protocol: none

- **A field-backed lookup param reads the field's `allowCreate`.** A param written `{ field, objectOverride }` already took the field's `lookupFilters`, `lookupColumns`, `lookupPageSize` and `descriptionField`, but not `allowCreate`. As a result, a field declaring `allowCreate: false` still showed "+ New" in an action's picker. `resolveActionParams` now copies it, app-shell's `paramToField` forwards it to the record-header dialog's picker, and the selection toolbar's dialog carries it through `resolvePromotedBulkParams`. Both the desktop popover and the phone drawer honour it. `@object-ui/core`'s `ActionParamDef` gains the optional `allowCreate` member it travels on. An author who writes `allowCreate` on a raw param is warned by name in development, like the other inherited picker keys: the spec's `ActionParamSchema` does not declare it.
- **A quick-created record is selected only if the picker could have offered it.** The create form accepts whatever the user enters, so the new record can fail the field's `lookupFilters`, for example a `draft` where the field asks for `approved`. The picker used to select it anyway, and the save or action that read the field then refused it. The picker now re-reads the new id through its own filter, the field's `lookupFilters` and `dependsOn` scope combined with the id. If the server does not return the record, it is not selected, and the picker reopens with the line `lookup.createdOutsideFilters` ("The record was created, but it does not match this field's filters, so it cannot be chosen here."), in every shipped locale. If the check itself fails, the record is not selected either, and the line `lookup.createdUnchecked` says the record was created but could not be checked, so the user searches for it instead of creating a duplicate. A picker with no filter selects the new record as before, without the extra read.
- **A create notice no longer hides the candidate list.** A create notice (the two lines above, or a failed inline create) now sits above the list instead of replacing it, so the user can pick an existing record straight away. Closing the picker clears it. Before, a failed inline create hid the list and its create entry until the widget was remounted.
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
/**
* ObjectUI
* Copyright (c) 2024-present ObjectStack Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

/**
* A field-backed lookup param reads `allowCreate` from the field it borrows
* (objectstack#36865, half 1, the record-header path).
*
* The param `{ field, objectOverride }` already inherited the field's
* `lookupFilters`, `lookupColumns`, `lookupPageSize` and `descriptionField`,
* but not `allowCreate`, so a field declaring `allowCreate: false` still drew
* "+ New" in an action's picker. These rows run the real chain the record
* header's dialog runs — `resolveActionParam` → `paramToField` → `LookupField`
* — on both faces of the picker (the desktop popover and the phone drawer).
*
* - `allowCreate: false` on the field: no create entry, popover and drawer;
* - CONTROL, a field that allows create: the create entry shows on both.
*/
import { render, screen, fireEvent, waitFor, act, cleanup, within } from '@testing-library/react';
import '@testing-library/jest-dom';
import React from 'react';
import { describe, it, expect, vi, afterEach } from 'vitest';
import { LookupField, resolveActionParam } from '@object-ui/fields';
import { paramToField } from './paramToField';

const realInnerWidth = Object.getOwnPropertyDescriptor(window, 'innerWidth');
const realMatchMedia = window.matchMedia;

function setViewportWidth(width: number) {
Object.defineProperty(window, 'innerWidth', { writable: true, configurable: true, value: width });
window.matchMedia = ((query: string) => ({
matches: window.innerWidth < 768,
media: query,
onchange: null,
addEventListener: () => {},
removeEventListener: () => {},
addListener: () => {},
removeListener: () => {},
dispatchEvent: () => false,
})) as any;
}

afterEach(() => {
cleanup();
if (realInnerWidth) Object.defineProperty(window, 'innerWidth', realInnerWidth);
window.matchMedia = realMatchMedia;
});

/** The borrowed field, as the expense app declares it. */
const requestField = (allowCreate: boolean | undefined) => ({
type: 'lookup',
label: 'Travel Request',
reference: 'crm_expense_request',
displayField: 'name',
lookupFilters: [{ field: 'status', operator: 'eq', value: 'approved' }],
...(allowCreate === undefined ? {} : { allowCreate }),
});

function widgetFieldFor(allowCreate: boolean | undefined) {
const resolved = resolveActionParam(
{ field: 'crm_expense_request', objectOverride: 'crm_expense_report' } as any,
{
objectName: 'crm_expense',
objects: [{ name: 'crm_expense_report', fields: { crm_expense_request: requestField(allowCreate) } }],
fieldLabel: (_o: string, _f: string, fallback: string) => fallback,
} as any,
);
return paramToField(resolved);
}

/** Open the picker on the given face and report whether it offers create. */
async function offersCreate(allowCreate: boolean | undefined, face: 'popover' | 'drawer'): Promise<boolean> {
setViewportWidth(face === 'drawer' ? 390 : 1280);
const field = widgetFieldFor(allowCreate);
const ds = {
find: vi.fn(async () => ({ data: [{ id: 'r1', name: 'Shanghai trip', status: 'approved' }], total: 1 })),
findOne: vi.fn(),
create: vi.fn(),
update: vi.fn(),
delete: vi.fn(),
};
render(<LookupField field={field as any} value={undefined} onChange={vi.fn()} readonly={false} dataSource={ds as any} />);
await act(async () => {
fireEvent.click(screen.getByTestId(`lookup-trigger-${field.name}`));
});
const panel = await screen.findByTestId(face === 'drawer' ? 'lookup-drawer' : 'lookup-popover');
await waitFor(() => expect(within(panel).getAllByRole('option')).toHaveLength(1));
return within(panel).queryByTestId('lookup-create-new') !== null;
}

describe('a field-backed action param honours the borrowed field\'s allowCreate (objectstack#36865)', () => {
it('the resolved widget field carries the field\'s allowCreate', () => {
expect(widgetFieldFor(false).allowCreate).toBe(false);
expect(widgetFieldFor(true).allowCreate).toBe(true);
});

it('allowCreate: false — no create entry in the desktop popover', async () => {
expect(await offersCreate(false, 'popover')).toBe(false);
});

it('allowCreate: false — no create entry in the phone drawer', async () => {
expect(await offersCreate(false, 'drawer')).toBe(false);
});

it('CONTROL — allowCreate: true shows the create entry in the popover', async () => {
expect(await offersCreate(true, 'popover')).toBe(true);
});

it('CONTROL — allowCreate: true shows the create entry in the drawer', async () => {
expect(await offersCreate(true, 'drawer')).toBe(true);
});
});
3 changes: 3 additions & 0 deletions ui/packages/app-shell/src/utils/paramToField.ts
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,9 @@ export function paramToField(param: ActionParamDef): Record<string, any> {
lookupColumns: param.lookupColumns,
lookupFilters: param.lookupFilters,
lookupPageSize: param.lookupPageSize,
// The borrowed field's `allowCreate`, the spelling `LookupField` reads;
// undefined leaves the picker's own default in place.
allowCreate: param.allowCreate,
// ⭐ objectui#7357 retired `depends_on`, objectui's snake_case twin of
// the spec's field-level cascade key. This emit was the ONE in-repo
// framework producer of that spelling on a widget field-metadata bag —
Expand Down
6 changes: 6 additions & 0 deletions ui/packages/core/src/actions/ActionRunner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -976,6 +976,12 @@ export interface ActionParamDef {
lookupFilters?: unknown[];
/** Page size for the typeahead popover. */
lookupPageSize?: number;
/**
* The field's `allowCreate` (`@objectstack/spec` `FieldSchema.allowCreate`):
* `false` keeps quick-create ("+ New") out of the param's picker. Absent, the
* picker applies its own default.
*/
allowCreate?: boolean;
/** Form-field dependencies that gate / parameterise the picker query. */
dependsOn?: unknown[];

Expand Down
13 changes: 13 additions & 0 deletions ui/packages/fields/src/resolveActionParams.ts
Original file line number Diff line number Diff line change
Expand Up @@ -333,6 +333,7 @@ export const RESOLVED_ONLY_PARAM_KEYS: Readonly<Record<string, string>> = (() =>
lookupColumns: fromField,
lookupFilters: fromField,
lookupPageSize: fromField,
allowCreate: fromField,
dependsOn: fromField,
};
})();
Expand Down Expand Up @@ -462,6 +463,13 @@ interface RuntimeField {
lookupFilters?: unknown[];
lookup_filters?: unknown[];
lookupPageSize?: number;
/**
* `@objectstack/spec`'s `FieldSchema.allowCreate`: whether the picker offers
* quick-create. Copied onto a field-backed lookup param with the picker keys
* above, so `allowCreate: false` on the field keeps "+ New" out of the
* param's picker too.
*/
allowCreate?: boolean;
dependsOn?: unknown[];
}

Expand Down Expand Up @@ -882,6 +890,11 @@ export function resolveActionParam(
lookupColumns: field.lookupColumns,
lookupFilters: field.lookupFilters ?? field.lookup_filters,
lookupPageSize: field.lookupPageSize,
// The field's quick-create switch travels with its other picker
// settings: without it a field that says `allowCreate: false` still
// drew "+ New" in an action's picker, and the record made there could
// be one the action must refuse.
allowCreate: field.allowCreate,
dependsOn: field.dependsOn,
}
: {};
Expand Down
Loading
Loading