Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion docs/features/code-based/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,14 @@ Code-based features let you extend forms-engine-plugin with custom TypeScript or

> Only introduce code-based customisations where there is genuine business need. Custom code becomes your team's responsibility to test, maintain and keep accessible.

## [Components](./code-based/components)
## [Custom Components](./code-based/components)

Build custom form components. Components can extend `ComponentBase` for display-only purposes or `FormComponent` to handle user input with validation, state management and rendering.

## [Custom Page Controllers](./code-based/page-controllers)

Attach bespoke server-side logic to a specific page. For example: running an auth check before render, enriching the view model with external data, or intercepting form submission.

## [Custom Services](./code-based/custom-services)

Replace the default form-loading or submission behaviour by providing your own `formsService`, `formSubmissionService` or `outputService` implementations via the plugin registration options.
Expand Down
214 changes: 214 additions & 0 deletions docs/features/code-based/page-controllers.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,214 @@
# Custom page controllers

Custom page controllers let you attach bespoke server-side logic to a specific page in your form. For example, fetching data from an external service before render, running an authorisation check, intercepting form submission, or writing additional data to session state.

Use a custom controller when you need server-side behaviour that cannot be expressed through configuration alone. If you want to avoid writing TypeScript altogether, explore the [configuration-based options](../configuration-based/index.md) first.

## How it works

Extend one of the built-in base classes, register it with the plugin, then reference it by name in your form definition.

**1. Create a controller class:**

```ts
import { QuestionPageController } from '@defra/forms-engine-plugin/controllers/QuestionPageController.js'

class EligibilityCheckController extends QuestionPageController {
makeGetRouteHandler() {
return async (request, context, h) => {
// your logic here
return super.makeGetRouteHandler()(request, context, h)
}
}
}
```

**2. Register it with the plugin:**

```ts
import { plugin } from '@defra/forms-engine-plugin'

await server.register({
plugin,
options: {
controllers: {
EligibilityCheckController
}
// ... other options
}
})
```

**3. Reference it in your form definition:**

```json
{
"path": "/eligibility-check",
"title": "Check your eligibility",
"controller": "EligibilityCheckController",
"components": []
}
```

The engine resolves built-in controller names first (such as `"TerminalPageController"` or `"SummaryPageController"`), then falls back to your `controllers` object. If no match is found, an error is thrown when the form is loaded.

## Choosing a base class

| Base class | Use when |
| ------------------------ | ---------------------------------------------------------------------------------------------------- |
| `QuestionPageController` | Your page has form components with validation and state. This covers most use cases. |
| `PageController` | Your page is display-only with no form submission — for example a static message page or a redirect. |

Both are imported from `@defra/forms-engine-plugin/controllers/<ClassName>.js`.

## Examples

- [Fetching data for the view model](#fetching-data-for-the-view-model)
- [Intercepting the GET handler](#intercepting-the-get-handler)
- [Writing to state on POST](#writing-to-state-on-post)
- [Display-only page (no form components)](#display-only-page-no-form-components)

### Fetching data for the view model

Override `makeGetRouteHandler()` to fetch data before the page renders and pass it to your Nunjucks template. Call `this.getViewModel()` to build the standard model, then spread in your additional data:

```ts
import { QuestionPageController } from '@defra/forms-engine-plugin/controllers/QuestionPageController.js'

import type { FormContext, FormRequest, FormResponseToolkit } from '@defra/forms-engine-plugin/types'

class SelectGrantSchemeController extends QuestionPageController {
makeGetRouteHandler() {
return async (request: FormRequest, context: FormContext, h: FormResponseToolkit) => {
const farmType = context.state.farmType

// Fetch grant schemes available for the user's farm type
const grantSchemes = await getEligibleGrantSchemes(farmType)

// Build the standard view model and add the fetched data
const viewModel = this.getViewModel(request, context)

return h.view(this.viewName, { ...viewModel, grantSchemes })
}
}
}
```

Your Nunjucks template can then reference `{{ grantSchemes }}`.

> **Note:** When you return directly from `makeGetRouteHandler()` without delegating to `super`, you own the full render. Standard GET behaviour — conditional component filtering, flash error handling, and URL pre-population — will not run. If your page relies on any of these, either delegate to `super.makeGetRouteHandler()(request, context, h)` and use a synchronous `getViewModel()` override instead, or replicate the behaviour you need in your handler.

### Intercepting the GET handler

Override `makeGetRouteHandler()` to run a check before the page renders and redirect if needed. Delegate to `super` when the check passes to preserve the standard rendering behaviour:

```ts
import { QuestionPageController } from '@defra/forms-engine-plugin/controllers/QuestionPageController.js'

import type { FormContext, FormRequest, FormResponseToolkit } from '@defra/forms-engine-plugin/types'

class GrantEligibilityController extends QuestionPageController {
makeGetRouteHandler() {
return async (request: FormRequest, context: FormContext, h: FormResponseToolkit) => {
const isEligible = await checkGrantEligibility(request)

if (!isEligible) {
return h.redirect(this.getHref('/not-eligible'))
}

return super.makeGetRouteHandler()(request, context, h)
}
}
}
```

### Writing to state on POST

Override `makePostRouteHandler()` to validate form input against an external service and store additional data in the session alongside the standard component values.

`context.errors` is populated by the engine before your handler runs. Check it first and re-render immediately if there are component-level validation errors, then apply your own logic:

```ts
import { QuestionPageController } from '@defra/forms-engine-plugin/controllers/QuestionPageController.js'

import type { FormContext, FormRequestPayload, FormResponseToolkit } from '@defra/forms-engine-plugin/types'

class PassportLookupController extends QuestionPageController {
makePostRouteHandler() {
return async (request: FormRequestPayload, context: FormContext, h: FormResponseToolkit) => {
// Re-render with component validation errors if any
if (context.errors) {
const viewModel = this.getViewModel(request, context)
return h.view(this.viewName, viewModel)
}

const passportNumber = context.payload.passportNumber

// Validate the submitted passport number against an identity service
const passport = await verifyPassport(passportNumber)

if (!passport) {
// Re-render with a custom error — the input passed component validation
// (format/required checks) but was not found in the external system
const viewModel = this.getViewModel(request, context)
viewModel.errors = [{ text: 'Passport number not recognised. Check and try again.' }]
return h.view(this.viewName, viewModel)
}

// Save the standard component state to the session
await this.setState(request, context.state)

// Merge additional data from the identity lookup into the session
// so it is available to later pages in the journey
await this.mergeState(request, context.state, {
verifiedName: passport.fullName,
nationality: passport.nationality
})

return this.proceed(request, h, this.getNextPath(context))
}
}
}
```

### Display-only page (no form components)

Extend `PageController` for a page with no form submission. Override `makeGetRouteHandler()` and render using `this.viewName` and `this.viewModel`:

```ts
import { PageController } from '@defra/forms-engine-plugin/controllers/PageController.js'

import type { FormContext, FormRequest, FormResponseToolkit } from '@defra/forms-engine-plugin/types'

class IneligiblePageController extends PageController {
makeGetRouteHandler() {
return async (_request: FormRequest, _context: FormContext, h: FormResponseToolkit) => {
return h.view(this.viewName, this.viewModel)
}
}
}
```

`this.viewModel` contains the standard page properties (title, phase banner, service URL, feedback link). Set the `view` property on the page definition to use a custom Nunjucks template — see [Page views](./page-views.md).

## Reference

### What QuestionPageController gives you

`QuestionPageController` has validation, state management, and routing logic built in. When you extend it, you get this behaviour for free and only need to override the parts relevant to your use case:

- **Schema validation** — the components declared in the form definition have their Joi schemas combined automatically. On POST, the payload is validated before your handler runs. If validation fails, `context.errors` is populated and the page is re-rendered with error messages.
- **Session state** — `context.state` is pre-populated from the session cache before your handler is called. The `setState()` and `mergeState()` methods write back to the cache.
- **Conditional routing** — `getNextPath(context)` evaluates any conditions defined in the form and returns the correct path for the next page.
- **Back link** — the back link is generated automatically based on the user's navigation history.
- **Save and exit** — if `allowSaveAndExit` is `true` and the `saveAndExit` plugin option is configured, the secondary button and its handler are wired up for you.

### Overridable members

| Member | Description |
| -------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `viewName` | The Nunjucks template rendered for this page. Defaults to `'index'`. Set `view` on the page definition to override. |
| `allowSaveAndExit` | Whether the "Save and exit" button is shown. `true` on `QuestionPageController`, `false` on `PageController`. Override as a class property to change the default. |
| `getViewModel(request, context)` | Returns the view model passed to the Nunjucks template. Override to add or modify properties synchronously. Only available on `QuestionPageController`. |
| `makeGetRouteHandler()` | Returns the async GET handler function. Override to control page load behaviour, including async data fetching. |
| `makePostRouteHandler()` | Returns the async POST handler function. Override to control form submission behaviour and write custom data to state. |
43 changes: 2 additions & 41 deletions docs/plugin-options.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,48 +30,9 @@ See [our services documentation](./features/code-based/custom-services).

### Custom controllers

The `controllers` option lets you register custom page controller classes that extend the built-in `PageController`. A custom controller is tied to a page in your form definition by setting the page's `controller` property to the key you register it under.
The `controllers` option lets you register custom page controller classes. A custom controller is tied to a page in your form definition by setting the page's `controller` property to the key you register it under.

```ts
import { PageController } from '@defra/forms-engine-plugin/controllers/PageController.js'
import { type FormModel } from '@defra/forms-engine-plugin/types'
import { type Page } from '@defra/forms-model'

class ConfirmationPageController extends PageController {
constructor(model: FormModel, pageDef: Page) {
super(model, pageDef)
}

makeGetRouteHandler() {
return async (request, h) => {
// custom logic before rendering
return h.view(this.viewName, { ...await this.getViewModel(request) })
}
}
}

await server.register({
plugin,
options: {
controllers: {
ConfirmationPageController
}
}
})
```

In your form definition, set the `controller` property of any page to the same key:

```json
{
"path": "/confirmation",
"title": "Confirmation",
"controller": "ConfirmationPageController",
"components": []
}
```

When the engine instantiates pages, it first checks for a matching built-in controller, then falls back to the `controllers` map. If no match is found the default `PageController` is used.
See [Custom page controllers](./features/code-based/page-controllers.md) for a full guide including examples and a reference of overridable members.

### Nunjucks configuration

Expand Down
10 changes: 10 additions & 0 deletions scripts/generate-component-docs.js
Original file line number Diff line number Diff line change
Expand Up @@ -1059,6 +1059,16 @@ function generatePagesIndex() {
lines.push(`- [**${label}**](./${slug}.mdx) — ${description}`)
}

lines.push(``)
lines.push(`## Build your own page type`)
lines.push(``)
lines.push(
`If none of the built-in page types meet your needs, you can write a custom page controller by extending \`QuestionPageController\` (for pages with form components) or \`PageController\` (for display-only pages). Custom controllers are registered via the \`controllers\` plugin option and referenced in your form definition by name.`
)
lines.push(``)
lines.push(
`See [Custom page controllers](../code-based/page-controllers.md) for a full guide.`
)
lines.push(``)
return lines.join('\n')
}
Expand Down
Loading
Loading