# Cascading selects

URL: https://docs.forms.saastro.io/docs/recipes/cascading-selects
> Country, region and city selects where each one loads its options from the value above, with optionsSource and {{field}} placeholders.

# Cascading selects

## What it combines

- **`optionsSource`** — a serialisable options loader: `url`, plus `path`, `labelKey`, `valueKey` when the response is not already `[{ label, value }]` ([Types](/docs/types))
- **`{{field}}` placeholders** in the `url` — each one makes the field depend on another
- **Select fields** — the control stays disabled until its parent has a value

```tsx
import { FormBuilder } from '@saastro/forms';

/**
 * Country → region → city. Each select asks its own endpoint, and the `{{field}}` in the URL
 * is what makes it depend on the one above: no value yet → no request and the control stays
 * disabled; the value changes → options are dropped, requested again and this field is cleared.
 */
export function createConfig({ base = '' }: { base?: string } = {}) {
  return FormBuilder.create('cascading-selects')
    .layout('manual')
    .columns(12)
    .addField('country', (f) =>
      f
        .type('select')
        .label('Country')
        .required()
        .options([
          { value: 'es', label: 'Spain' },
          { value: 'fr', label: 'France' },
        ])
        .columns({ default: 12, md: 4 }),
    )
    .addField('region', (f) =>
      f
        .type('select')
        .label('Region')
        .required()
        .optionsSource({ url: `${base}/demo/regions/{{country}}.json` })
        .columns({ default: 12, md: 4 }),
    )
    .addField('city', (f) =>
      f
        .type('select')
        .label('City')
        .required()
        .optionsSource({ url: `${base}/demo/cities/{{region}}.json` })
        .columns({ default: 12, md: 4 }),
    )
    .addStep('place', ['country', 'region', 'city'])
    .initialStep('place')
    .build();
}
```

## The code

The **Code** tab above is the whole form. Each dependent select declares only its endpoint:

```ts
.addField('region', (f) =>
  f.type('select').label('Region').required()
    .optionsSource({ url: '/api/regions/{{country}}' }),
)
```

## How it works

- **Dependencies come from the URL** — every `{{field}}` in `url` counts, and `dependsOn: ['other']` adds fields the server reads from somewhere else.
- **Nothing is requested while a parent is empty**, and the control is disabled.
- **When a parent changes**, the old options are dropped and the new ones requested. If the parent is emptied the field's value is cleared, and when the new options arrive a value that is no longer among them is removed. Because the region is cleared, the city loses its parent too, so the change cascades down.
- **Values are URL-encoded** (`encodeURIComponent`) before they replace the placeholder.

## Caveats

- **A placeholder cannot sit in the host** — only after the origin (`https://api.example.com/regions/{{country}}` is fine, `https://{{country}}.example.com` is not).
- **Dependencies must be single values** (text or number). A multiple field as a parent has no value to substitute and leaves the options empty.
- **`loadOptions` wins** over `optionsSource` when both are set, and it is a function: it does not survive the Hub or the builder's JSON.
- **The endpoint runs in the browser**, so it cannot hold secrets, and it must allow your origin (CORS).
- **Do not trust the browser's choice** — the options are fetched on the client, so on the server check the country, region and city against your own data.

## Variations

- Point `path` at `data.items` and set `labelKey`/`valueKey` for an existing API.
- Use `combobox` with `serverSearch` and `searchParam` for long lists.
- Add `dependsOn` for a parent that is not in the URL (a header, a cookie the endpoint reads).

## Related

- [Types](/docs/types)
- [Validate the same rules on the server](/docs/recipes/server-validation)
- [Lookup: autofill from a postcode](/docs/recipes/lookup-autofill)
