fix(site/src/pages/CreateUserPage): show and link the organization field error (#32768)

On Create user, the Organization field was a hand-built `Label` and
`OrganizationAutocomplete`, so validation errors were never shown next
to it or linked to it. This PR routes the field through `FormField` with
a `control` render prop, the same pattern `TemplateCustomizationsStep`
and `ChatProjectDialog` use:

- The trigger gets `aria-invalid` and an `aria-describedby` that points
at the current error.
- The error text renders under the field, and the trigger gets the
destructive border like the other fields.
- A client-side `required` rule shows "Please select an organization."
when the user submits without one. Before, the request went to the
server with an empty ID.
- Backend `organization_ids` validation errors map to the field.
- The label shows the required asterisk like the other required fields.
The e2e `createUser` helper already looks up `getByLabel("Organization
*")`.

Closes DEQ-658

| Ticket | UI surface | Screenshots |
|---|---|---|
| DEQ-658 | `/deployment/users/create` with multiple organizations,
story `pages/CreateUserPage` | [DEQ-658
screenshots](https://linear.app/codercom/issue/DEQ-658#comment-a0c5d533)
|

Changes:
- `CreateUserForm.tsx`: use `FormField` for the organization field, add
the `required` rule, and map the `organization_ids` backend field.
- `CreateUserForm.test.tsx`: submitting without an organization
describes the trigger with the error and does not call `onSubmit`. This
test fails on `main`.
- `CreateUserForm.stories.tsx`: add an `OrganizationRequired` story for
the error state. The `WithOrganizations` combobox query becomes
`/^Organization/`, because the accessible name now includes the
asterisk.

<details>
<summary>Decision log and notes</summary>

- `FormField` with `control` was chosen over hand-wiring `aria-*`. It is
the existing primitive, and two other organization pickers already use
it.
- The hard-coded `id="organization"` was dropped in favor of the ID that
`FormField` generates. Nothing referenced it.
- Dropped review findings:
- DF5 nit: when the permitted organizations query fails, the field shows
the required error over an empty picker. That load-error handling is
pre-existing and out of scope for this ticket.
- TS1 nit: `WithOrganizations` still has two `aria-expanded` assertions
in its `play`. They are pre-existing, and this diff only changes the
query.
- axe on the error state finds no violations.

</details>

🤖 Generated by Coder Agents on behalf of @bartekgatzcoder.
This commit is contained in:
Bartek Gatz authored and GitHub committed 2026-11-26 10:34:20 +01:00
1 parent 0fc090ae40
commit 3ba7199fde
3 files changed
+77 -18

No files matched your search

@@ -130,7 +130,7 @@ export const WithOrganizations: Story = {
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
const organization = canvas.getByRole("combobox", {
name: "Organization",
name: /^Organization/,
});
await expect(organization).toHaveAttribute("aria-expanded", "false");
await userEvent.click(organization);
@@ -169,6 +169,33 @@ export const LoginTypeError: Story = {
},
};
export const OrganizationRequired: Story = {
parameters: {
queries: [
{
key: permittedOrganizationsKey({
object: { resource_type: "organization_member" },
action: "create",
}),
data: [MockOrganization, MockOrganization2],
},
],
},
args: {
showOrganizations: true,
},
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
await userEvent.type(canvas.getByLabelText(/username/i), "someuser");
await userEvent.type(
canvas.getByLabelText(/email/i),
"someone@example.com",
);
await userEvent.type(canvas.getByTestId("password-input"), "SomePassword!");
await userEvent.click(canvas.getByRole("button", { name: /save/i }));
},
};
export const GeneralError: Story = {
args: {
error: mockApiError({
@@ -1,5 +1,6 @@
import { screen, waitFor, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { HttpResponse, http } from "msw";
import {
assignableRole,
MockAuditorRole,
@@ -8,6 +9,7 @@ import {
mockApiError,
} from "#/testHelpers/entities";
import { render } from "#/testHelpers/renderHelpers";
import { server } from "#/testHelpers/server";
import { CreateUserForm } from "./CreateUserForm";
const renderForm = (
@@ -92,6 +94,24 @@ describe("CreateUserForm", () => {
);
});
it("describes the organization trigger with its validation error", async () => {
server.use(http.get("/api/v2/organizations", () => HttpResponse.json([])));
const user = userEvent.setup();
const { onSubmit } = renderForm({ showOrganizations: true });
await user.type(screen.getByLabelText(/username/i), "someuser");
await user.type(screen.getByLabelText(/email/i), "someone@example.com");
await user.type(screen.getByTestId("password-input"), "SomePassword!");
await user.click(screen.getByRole("button", { name: /save/i }));
await waitFor(() =>
expect(
screen.getByRole("combobox", { name: /organization/i }),
).toHaveAccessibleDescription("Please select an organization."),
);
expect(onSubmit).not.toHaveBeenCalled();
});
it("submits the roles checked in the Roles group", async () => {
const user = userEvent.setup();
const { onSubmit } = renderForm({
@@ -13,7 +13,6 @@ import { ErrorAlert } from "#/components/Alert/ErrorAlert";
import { Button } from "#/components/Button/Button";
import { FormFields, FormFooter } from "#/components/Form/Form";
import { FormField } from "#/components/FormField/FormField";
import { Label } from "#/components/Label/Label";
import { OrganizationAutocomplete } from "#/components/OrganizationAutocomplete/OrganizationAutocomplete";
import { SelectField } from "#/components/SelectField/SelectField";
import {
@@ -63,6 +62,7 @@ const validationSchema = Yup.object({
.required("Please enter an email address."),
otherwise: (schema) => schema.optional(),
}),
organization: Yup.string().required("Please select an organization."),
login_type: Yup.string()
.oneOf(Object.keys(loginTypeOptions))
.required("Please select a login type."),
@@ -221,6 +221,9 @@ const CreateUserFormFields: React.FC<CreateUserFormFieldsProps> = ({
helperText: "Authentication method for this user.",
});
const loginTypeOptionId = useId();
const organizationField = getFieldHelpers("organization", {
backendFieldName: "organization_ids",
});
return (
<div>
@@ -248,22 +251,31 @@ const CreateUserFormFields: React.FC<CreateUserFormFieldsProps> = ({
)}
<FormFields>
{showOrganizations && (
<div className="flex flex-col gap-2">
<Label htmlFor="organization">Organization</Label>
<OrganizationAutocomplete
id="organization"
required
value={selectedOrg}
options={orgOptions}
onChange={(newValue) => {
setSelectedOrg(newValue);
void form.setFieldValue(
"organization",
newValue?.id ?? "",
);
}}
/>
</div>
<FormField
field={organizationField}
label="Organization"
required
control={(controlProps) => (
<OrganizationAutocomplete
{...controlProps}
required
triggerClassName={
organizationField.error
? "border-border-destructive"
: undefined
}
value={selectedOrg}
options={orgOptions}
onChange={(newValue) => {
setSelectedOrg(newValue);
void form.setFieldValue(
"organization",
newValue?.id ?? "",
);
}}
/>
)}
/>
)}
<SelectField