# Reading forms – Form Builder

Fetch a form with its blocks, resolve the blocks and merge texts per key along the locale chain.

The helpers on this page come from the sample project, [`examples/form-builder-next`](https://github.com/san26786/geecon-contentful/tree/main/examples/form-builder-next). It runs on bundled data with no setup. Copy the `src/lib/form-builder/` folder into your project. Its only dependency is `zod`.

Form Builder doesn't provide a submission endpoint. Your website decides where answers go.

## Fetch a form with its blocks

Ask the Content Delivery API for the form by ID, with every locale and `include` so its blocks come back in the same response. The sample uses Contentful's JavaScript SDK, the `contentful` package, on the server only. `withAllLocales` asks for every locale, and `withoutLinkResolution` keeps the raw `includes` that `resolveForm` reads:

```ts title="examples/form-builder-next/src/lib/contentful.ts (trimmed)"
const client = () =>
  createClient({
    space: CONTENTFUL_SPACE_ID ?? "",
    accessToken: CONTENTFUL_DELIVERY_TOKEN ?? "",
    environment: CONTENTFUL_ENVIRONMENT, // defaults to "master"
  }).withAllLocales.withoutLinkResolution;

const { items, includes } = (isConfigured
  ? await client().getEntries({ content_type: CONTENTFUL_CONTENT_TYPE_ID, "sys.id": id, include: 2 })
  : fixture) as unknown as CdaResponse;
```

This is the request the SDK sends:

```text
GET /spaces/{space}/environments/master/entries?content_type=formBuilderForm&sys.id={id}&include=2&locale=*
```

- The Delivery API returns only published entries. Publish a form and every block it uses.
- The sample caches each form for 60 seconds with Next.js `unstable_cache`, so a published change can take up to a minute to show. It passes only known locale codes to the cache, so an unknown `?locale=` value can't fill it up.
- Contentful can't combine field filters with `locale=*`. To list forms, fetch by content type and keep the entries whose `kind` is `form`, as the sample does in code.
- A form's `definition` and `kind` are under the default locale. Its `texts` are keyed by locale.

## Resolve the form

`resolveForm` takes the entry, the included entries and the locale chain (the visitor's locale, its fallbacks, then the default locale). It expands blocks, merges texts and returns a form your UI can use.

```ts title="examples/form-builder-next/src/lib/form-builder/resolve.ts (trimmed)"
export function resolveForm(entry: CdaEntry, includes: CdaEntry[], localeChain: string[]): ResolvedForm {
  // Non-localized fields (definition, kind, title) live under the default locale, the last in the chain.
  const defaultLocale = localeChain.at(-1) ?? "en-US";
  const blocks = new Map(includes.map((e) => [e.sys.id, e]));
  // ...
  for (const raw of rawItems(page)) {
    if (raw.type === "block" && typeof raw.entryId === "string") {
      const block = blocks.get(raw.entryId);
      if (!block) {
        missing.add(raw.entryId); // reported in `missingBlocks`; the rest of the form still renders
        continue;
      }
      // The block's items take the place of the block item.
      // ...
    } else if (isKnown(raw)) {
      items.push(raw);
    }
  }
  // ...
  return { id, title, definition: resolved, texts: { ...blockTexts, ...textsOf(entry) }, missingBlocks: [...missing] };
}
```

It never throws. An unknown item type is skipped, a block that isn't in the response is listed in `missingBlocks`, and a block inside a block is ignored. An item's own `showWhen` rule wins over the rule on the block that holds it.

## Merge texts per key

A translated locale holds only some keys, so merge along the locale chain. The first locale that has a key wins, and the default locale is last.

```ts title="examples/form-builder-next/src/lib/form-builder/texts.ts"
/** Merge per key along the locale chain. `chain[0]` is the visitor's locale, the last is the default. */
export function mergeTexts(chain: (Texts | undefined | null)[]): Texts {
  return Object.assign({}, ...[...chain].reverse().filter(Boolean));
}
```

Build the chain from Contentful's locale list (`client().getLocales()`), following each locale's `fallbackCode` and ending at the default locale:

```ts title="examples/form-builder-next/src/lib/contentful.ts (trimmed)"
function localeChain(locale: string | undefined, all: Locale[]): string[] {
  const byCode = new Map(all.map((l) => [l.code, l]));
  const defaultCode = all.find((l) => l.default)?.code ?? "en-US";
  const chain = [byCode.has(locale ?? "") ? (locale as string) : defaultCode];
  for (let next = byCode.get(chain.at(-1) as string)?.fallbackCode; next && !chain.includes(next);) {
    chain.push(next);
    next = byCode.get(next)?.fallbackCode;
  }
  if (!chain.includes(defaultCode)) chain.push(defaultCode);
  return chain;
}
```

## Open, closed and scheduled

`effectiveStatus` turns `status` and `schedule` into one answer. Closed wins. A date that can't be parsed counts as absent.

```ts title="examples/form-builder-next/src/lib/form-builder/status.ts"
export function effectiveStatus(def: FormDefinition, now: Date): "open" | "closed" | "scheduled" | "ended" {
  if (def.status === "closed") return "closed";
  const opens = time(def.schedule?.opensAt);
  const closes = time(def.schedule?.closesAt);
  if (opens !== undefined && now.getTime() < opens) return "scheduled";
  if (closes !== undefined && now.getTime() >= closes) return "ended";
  return "open";
}
```

When the form isn't open, show the `form.closed` text instead of the form.

## Apply `showWhen` rules

`isVisible` says whether an item is shown for the current answers. An item is visible when it has no rule, or when its controlling field is visible and the answer matches. A loop counts as hidden.

```ts title="examples/form-builder-next/src/lib/form-builder/visibility.ts"
export function isVisible(item: FormField | LayoutItem, values: Record<string, unknown>, items: Item[], seen = new Set<string>()): boolean {
  if (!item.showWhen) return true;
  if (seen.has(item.id)) return false;
  const controller = items.find((i) => i.id === item.showWhen?.field);
  if (!controller || controller === item) return false;
  return (
    isVisible(controller, values, items, new Set(seen).add(item.id)) &&
    ruleMatches(item.showWhen, values[controller.id])
  );
}
```

Use it to decide what to render and what to validate. Don't submit a hidden field's answer.
