---
title: "Form Project"
description: "Derafu Form"
type: "docs"
category: "doc"
tags: [php]
authors: [Anonymous]
date: "2026-11-09"
last_update: "2026-11-09"
time_minutes: 1
draft: false
unlisted: false
url: "https://www.derafu.dev/docs/ui/form"
---

# Derafu Form



---

## Introduction

PHP form library with declarative JSON Schema and UI Schema definitions, rendering, validation and CSRF protection

# Declarative Forms, Seamless Rendering

[![GitHub](https://img.shields.io/badge/github-derafu%2Fform-blue?logo=github)](https://github.com/derafu/form)
![GitHub last commit](https://img.shields.io/github/last-commit/derafu/form/main)
![CI Workflow](https://github.com/derafu/form/actions/workflows/ci.yml/badge.svg?branch=main&amp;event=push)
![GitHub code size in bytes](https://img.shields.io/github/languages/code-size/derafu/form)
![GitHub Issues](https://img.shields.io/github/issues-raw/derafu/form)
![Total Downloads](https://poser.pugx.org/derafu/form/downloads)
![Monthly Downloads](https://poser.pugx.org/derafu/form/d/monthly)

A modern PHP form library that leverages a declarative, schema-based approach to form definition and rendering, compatible with JSON Forms while providing a powerful backend-centric workflow.

## Key Features

- **Schema-Based Form Definition**: Define forms using structured arrays that clearly separate data schemas from UI layouts.
- **Backend-First Approach**: Built for PHP developers who want control over form generation with minimum effort.
- **Symfony-Compatible Twig Extensions**: Familiar syntax for Symfony developers, minimizing learning curve.
- **Decoupled Rendering System**: Separate your form logic from its presentation with specialized renderers.
- **JSON Forms Compatibility**: Define once, use anywhere - same schema can be used with frontend JSON Forms library.
- **Automatic Form Generation**: Generate form UI schemas automatically from your data models.
- **Extensible Architecture**: Easily add custom types, layouts and renderers.
- **Translatable, Optionally**: Validation error messages and input action
  labels (show/hide password, copy, etc.) can be translated by wiring an
  optional translator — see [Translations](translations).

## Why Choose This Library?

### Compared to Traditional PHP Form Libraries

Traditional PHP form libraries often tightly couple form definition with HTML generation, making it difficult to separate concerns. This library takes a different approach:

1. **Declarative Rather Than Imperative**: Define _what_ your form should be rather than _how_ it should be built, step by step.
2. **Clear Separation of Concerns**: Schema (data structure) is separate from UI schema (presentation) and data (values).
3. **Powerful Layouts Without HTML Knowledge**: Create complex, multi-column layouts without writing HTML.

### Compared to Frontend-Only Solutions

Unlike frontend-only form builders, this library:

1. **Keeps Validation Logic Server-Side**: Where it belongs for security-critical applications.
2. **Provides PHP-Native Form Definition**: No need to write JavaScript to define your forms.
3. **Works With or Without JavaScript**: Generate the same forms for both traditional and SPA applications.

## Installation

Install the library using Composer:

```shell
composer require derafu/form
```

## Basic Usage

### Creating a Simple Form

```php
// Define the form structure.
$definition = [
    &#039;schema&#039; =&gt; [
        &#039;type&#039; =&gt; &#039;object&#039;,
        &#039;properties&#039; =&gt; [
            &#039;name&#039; =&gt; [
                &#039;type&#039; =&gt; &#039;string&#039;,
                &#039;title&#039; =&gt; &#039;Full Name&#039;,
            ],
            &#039;email&#039; =&gt; [
                &#039;type&#039; =&gt; &#039;string&#039;,
                &#039;format&#039; =&gt; &#039;email&#039;,
                &#039;title&#039; =&gt; &#039;Email Address&#039;,
            ],
        ],
        &#039;required&#039; =&gt; [&#039;name&#039;, &#039;email&#039;],
    ],
    &#039;uischema&#039; =&gt; [
        &#039;type&#039; =&gt; &#039;VerticalLayout&#039;,
        &#039;elements&#039; =&gt; [
            [
                &#039;type&#039; =&gt; &#039;Control&#039;,
                &#039;scope&#039; =&gt; &#039;#/properties/name&#039;,
            ],
            [
                &#039;type&#039; =&gt; &#039;Control&#039;,
                &#039;scope&#039; =&gt; &#039;#/properties/email&#039;,
            ],
        ],
    ],
    &#039;data&#039; =&gt; [
        &#039;name&#039; =&gt; &#039;&#039;,
        &#039;email&#039; =&gt; &#039;&#039;,
    ],
];

// Create the form.
$form = $formFactory-&gt;create($definition);
```

### Rendering with Twig

```twig
{# Simple rendering of the entire form. #}
{{ form(form) }}

{# Or with more control over individual components. #}
{{ form_start(form) }}
    {{ form_row(form.fields.name) }}
    {{ form_row(form.fields.email) }}
    &lt;button type=&quot;submit&quot; class=&quot;btn btn-primary&quot;&gt;Submit&lt;/button&gt;
{{ form_end(form) }}
```

## Automatic Schema Generation

The library can automatically generate a schema from your data:

```php
$definition = [
    &#039;data&#039; =&gt; [
        &#039;name&#039; =&gt; &#039;John Doe&#039;,
        &#039;email&#039; =&gt; &#039;john.doe@example.com&#039;,
        &#039;age&#039; =&gt; 34,
        &#039;birthdate&#039; =&gt; &quot;1990-01-01&quot;,
    ],
];

// Schema and UI schema will be automatically generated.
$form = $formFactory-&gt;create($definition);
```

## Integration with JSON Forms

This library&#039;s form definitions are compatible with the [JSON Forms](https://jsonforms.io) JavaScript library, allowing you to use the same definitions for both server-side and client-side rendering:

```html
&lt;div id=&quot;json-form-container&quot;&gt;&lt;/div&gt;
```

```javascript
// https://raw.githubusercontent.com/derafu/form/refs/heads/main/assets/js/jsonforms-viewer.js
import &#039;./jsonforms-viewer.js&#039;;

// Render the form and save the reference.
const formDefinition = {{ jsonFormsDefinition | json_encode | raw }};
const formInstance = window.renderJsonForm(&#039;json-form-container&#039;, formDefinition);
// You can now use `formInstance` to get the form data or its errors.
```

### Development Requirements

To render forms using JSON Forms you must install:

```shell
npm install @jsonforms/core @jsonforms/react @jsonforms/material-renderers \
    react react-dom @mui/material @emotion/react @emotion/styled
```

## Form Layouts

The UI schema supports various layout types by default:

- **VerticalLayout**: Fields stacked vertically.
- **HorizontalLayout**: Fields arranged horizontally, in columns of the same width or of the size that each one asks for, see [Rendering options](rendering-options).
- **Group**: Logical grouping of fields, often with a label.
- **Categorization**: Tab-based layouts for complex forms.

Example:

```php
$uischema = [
    &#039;type&#039; =&gt; &#039;VerticalLayout&#039;,
    &#039;elements&#039; =&gt; [
        [
            &#039;type&#039; =&gt; &#039;Group&#039;,
            &#039;label&#039; =&gt; &#039;Personal Information&#039;,
            &#039;elements&#039; =&gt; [
                [&#039;type&#039; =&gt; &#039;Control&#039;, &#039;scope&#039; =&gt; &#039;#/properties/name&#039;],
                [&#039;type&#039; =&gt; &#039;Control&#039;, &#039;scope&#039; =&gt; &#039;#/properties/email&#039;],
            ],
        ],
        [
            &#039;type&#039; =&gt; &#039;Group&#039;,
            &#039;label&#039; =&gt; &#039;Address&#039;,
            &#039;elements&#039; =&gt; [
                [&#039;type&#039; =&gt; &#039;Control&#039;, &#039;scope&#039; =&gt; &#039;#/properties/street&#039;],
                [&#039;type&#039; =&gt; &#039;Control&#039;, &#039;scope&#039; =&gt; &#039;#/properties/city&#039;],
            ],
        ],
    ],
];
```

## Guides

- [Validation](validation): how the rules that process the data are derived from the schema.
- [Required fields](required-fields): the marker of the label, the browser asking for the field, booleans that must be checked.
- [Rendering options](rendering-options): where the options come from, which one decides, layouts and columns.
- [Translations](translations), [CSRF protection](csrf) and [Captcha](captcha).




---

## Translations

Translations

# Translations

`derafu/form` has four independent, optional translation surfaces. All of them are
powered by [`derafu/translation`](https://www.derafu.dev/docs/core/translation), and all of them do
nothing unless you explicitly wire a translator — without one, everything
renders in English exactly as before.

## 1. Validation Error Messages

`FormDataProcessor` runs field values through
[`derafu/data-processor`](https://www.derafu.dev/docs/data/data-processor) rules. When a rule
fails, it throws a `Derafu\DataProcessor\Exception\ValidationException` (or
one of the other translatable exceptions from that package — see
[its Translations guide](https://www.derafu.dev/docs/data/data-processor)). `FormDataProcessor`
accepts an optional translator and locale; when given, it translates each
error before adding it to the result:

```php
final class FormDataProcessor implements FormDataProcessorInterface
{
    public function __construct(
        FormRulesResolverInterface $resolver,
        ProcessorInterface $processor,
        UiSchemaRuleEvaluatorInterface $evaluator = new UiSchemaRuleEvaluator(),
        ?TranslatorInterface $translator = null,
        ?string $locale = null,
    ) {
    }
}
```

Without a translator, `getErrors()` returns the untranslated (English)
messages — the exact same behavior as before this parameter existed.

## 2. Input Action Labels

Controls rendered with the `Control` UI schema type can declare
`options.actions` — input-group buttons like &quot;show/hide password&quot;,
&quot;generate a random password&quot;, or &quot;copy the field&#039;s value&quot;. Their labels
(and the default copy confirmation message) are resolved by
`InputActionResolver`, which also accepts an optional translator:

```php
final class InputActionResolver
{
    public function __construct(
        ?TranslatorInterface $translator = null,
        ?string $locale = null,
    ) {
    }
}
```

An explicit `label` or `message` given directly in `options.actions` is
always used as-is and never translated — only the three built-in defaults
are:

```php
[
    &#039;type&#039; =&gt; &#039;Control&#039;,
    &#039;scope&#039; =&gt; &#039;#/properties/password&#039;,
    &#039;options&#039; =&gt; [
        &#039;actions&#039; =&gt; [&#039;toggle-password&#039;],
    ],
]
```

`ElementRendererProvider` forwards `InputActionResolver` to `ControlRenderer`.
The service configuration injects the application&#039;s translator into that resolver.
For explicit PHP construction, inject a translator-aware resolver into the
provider (see [Activating It](#activating-it-plain-php) below).

## 3. The Texts of a Form

The titles, descriptions, labels, help texts, placeholders and options that the author of a form writes are translated when the form is created. The author writes them in English, as normal text, and each form says in which translation domain they are, with the option `translation_domain` (in the `options` of the definition, where the other options of the form are):

```yaml
# resources/forms/contact-form.yaml
options:
    translation_domain: contact-form

schema:
    type: object
    properties:
        name:
            type: string
            title: Your Name
uischema:
    type: VerticalLayout
    elements:
        - type: Control
          scope: &#039;#/properties/name&#039;
          options:
              placeholder: Type your name
```

`Derafu\Form\Factory\TranslatingFormFactory` decorates the form factory, which is where every form ends: the loaders (PHP, YAML and JSON) and whoever builds a definition by hand call `create()`. The text in English is the id of the translation, the domain is the `options.translation_domain` of the definition, and the language is the one of the translator when the form is created. A text without an entry in the catalogue stays as it was written, and a definition without `options.translation_domain` is not touched.

The catalogue is `resources/translations/&lt;domain&gt;+intl-icu.&lt;locale&gt;.php` in the directory of the resource provider of the package or the site. A site can have as many domains as it wants: every file of the directory is loaded.

### Which texts

Only these keys are texts. Everything else is data or configuration and is never translated.

| Where | Keys |
| --- | --- |
| The schema: the form and each property (also inside `items`, `$defs` and `definitions`) | `title`, `description` |
| The options of a property: each element of `oneOf`, `anyOf` and `allOf` | `title` |
| Each element of the UI schema (also inside `elements`, and inside `options.detail`) | `label`, and `text` for a `Label` |
| The `options` of an element | `placeholder`, `help`, `footer`, `error_message`, `label`, `unit`, `input_group_prepend_text`, `input_group_append_text` |
| The `choices` of an element (and `cascade.choices`) | The title of each choice: the values of the dict, never its keys (they are the values of the field) |

The list lives in `Derafu\Form\Translation\FormTexts`, and the factory and the audit use the same one, so what is translated and what is audited are always the same.

### What is not in the list: PHP

A form that needs to translate something that is not in the list (a text in `options.attr`, for example), or a text with parameters, is written in PHP. `PhpFormLoader` receives an optional translator, and when it has one the closure of the file gets in its context `translator` and `_t`, a function `(string $id, array $parameters = [], string $domain = &#039;messages&#039;)`. What the caller already put in the context under those names is not replaced:

```php
// resources/forms/profile.form.php
return function (array $context = []): array {
    return [
        &#039;options&#039; =&gt; [&#039;translation_domain&#039; =&gt; &#039;profile&#039;],
        &#039;schema&#039; =&gt; [
            &#039;type&#039; =&gt; &#039;object&#039;,
            &#039;properties&#039; =&gt; [
                &#039;name&#039; =&gt; [
                    &#039;type&#039; =&gt; &#039;string&#039;,
                    &#039;title&#039; =&gt; $context[&#039;_t&#039;](&#039;Hello {name}&#039;, [&#039;name&#039; =&gt; $context[&#039;user&#039;]], &#039;profile&#039;),
                ],
            ],
        ],
    ];
};
```

The result of the closure also goes through the factory, so the texts of the list are translated too if the definition has `options.translation_domain`. A text that was already translated has no entry in the catalogue and stays as it is.

### Auditing the texts

`Derafu\Form\Lint\FormTranslationAudit` reads the definitions of a directory (YAML, JSON and PHP) without running them and checks their texts against the catalogues of the package. It needs `symfony/yaml` and `nikic/php-parser`, as development dependencies. Like the audit of [`derafu/translation`](https://www.derafu.dev/docs/core/translation/lint), it only gives facts, and the test says which ones are a problem:

```php
$report = (new FormTranslationAudit())-&gt;audit(
    dirname(__DIR__, 2) . &#039;/resources/forms&#039;,
    new MyPackageTranslationResourceProvider(),
);

$this-&gt;assertFalse($report-&gt;nothingFound);
$this-&gt;assertSame([], $report-&gt;describe($report-&gt;dynamicTexts));
$this-&gt;assertSame([], $report-&gt;describe($report-&gt;withoutDomain));
$this-&gt;assertSame([], $report-&gt;describe($report-&gt;missingTranslations));
$this-&gt;assertSame([], $report-&gt;describe($report-&gt;notUsedBySources));
```

| Property | The fact |
| --- | --- |
| `texts` | The texts that can be read and have a domain. |
| `dynamicTexts` | Texts that are not a literal, so they can not be checked: a call of a local function (`$t(&#039;Name&#039;)`), a concatenation, a call of `_t` with a variable. |
| `withoutDomain` | Texts of definitions without `options.translation_domain`: they are not translated. |
| `missingTranslations` | Texts without an entry in the catalogue of their domain. |
| `notUsedBySources` | Entries of the catalogues, in the domains that the definitions use, that no text uses. If the domain is shared with templates or code, use it as a list to subtract from (the other audits flag these entries as unused). |

The calls `$context[&#039;_t&#039;](&#039;Text&#039;, [], &#039;domain&#039;)` are found wherever they are, because they are written for what is not in the list. To have a PHP form audited, write them with that form; a local function (`$t = fn ...`) works, but its texts are reported as dynamic and are not audited. A PHP definition is read when it is an array written in the file, and a part built in a variable is not read.

### The loaders in the container

`form-services.yaml` registers `PhpFormLoader` and `YamlFormLoader` for the forms of the application, with the directory `resources/forms` of the project (`&lt;name&gt;.form.php` and `&lt;name&gt;.form.yaml`). They are private services: an application that does not use them does not have them in its container. The `PhpFormLoader` gets the translator of the container, so its closures receive `_t`, and both create the form with the factory that translates. `FormLoaderInterface` is not set: which loader it is, or a chain of them (`ChainFormLoader`), is a decision of each application:

```yaml
services:
    Derafu\Form\Contract\Loader\FormLoaderInterface:
        alias: Derafu\Form\Loader\PhpFormLoader
```

## What Ships

`derafu/form` includes:

- `resources/translations/form+intl-icu.es.php` — a Spanish translation
  for the four strings `InputActionResolver` can produce (validation error
  messages come from `derafu/data-processor`&#039;s own translations instead —
  `derafu/form` doesn&#039;t duplicate them).
- `Derafu\Form\Translation\FormTranslationResourceProvider` — a
  `TranslationResourceProviderInterface` implementation pointing at that
  directory.
- `Derafu\Form\Factory\TranslatingFormFactory` and `Derafu\Form\Translation\FormTexts`
  (the texts of a form, section 3), and `Derafu\Form\Lint\FormTranslationAudit` to audit them.

Neither does anything on its own — `derafu/form` is a library, it doesn&#039;t
build or own a `Translator`.

## Activating It (Plain PHP)

```php
use Derafu\DataProcessor\Processor;
use Derafu\DataProcessor\Registrar\DefaultRuleRegistrar;
use Derafu\DataProcessor\RuleParser;
use Derafu\DataProcessor\RuleRegistry;
use Derafu\DataProcessor\RuleResolver;
use Derafu\DataProcessor\Translation\DataProcessorTranslationResourceProvider;
use Derafu\Form\Processor\FormDataProcessor;
use Derafu\Form\Processor\FormRulesResolver;
use Derafu\Form\Translation\FormTranslationResourceProvider;
use Derafu\Translation\TranslatorFactory;

$translator = TranslatorFactory::create(
    defaultLocale: &#039;es&#039;,
    fallbackLocales: [&#039;es&#039;, &#039;en&#039;],
    resourceProviders: [
        new DataProcessorTranslationResourceProvider(), // Validation error messages.
        new FormTranslationResourceProvider(),           // Input action labels.
    ],
);

$registry = new RuleRegistry();
(new DefaultRuleRegistrar())-&gt;register($registry);

$processor = new FormDataProcessor(
    new FormRulesResolver(),
    new Processor(new RuleResolver($registry), new RuleParser()),
    translator: $translator,
    locale: &#039;es&#039;,
);
```

For the action labels, build the renderer with a translator-aware
`ElementRendererProvider`:

```php
use Derafu\Form\Renderer\ElementRendererProvider;
use Derafu\Form\Renderer\ElementRendererRegistry;
use Derafu\Form\Renderer\FormRenderer;
use Derafu\Form\Renderer\Support\InputActionResolver;

$elementRegistry = new ElementRendererRegistry(new ElementRendererProvider(
    actionResolver: new InputActionResolver($translator, &#039;es&#039;),
));
$formRenderer = new FormRenderer($templateRenderer, $elementRegistry, $widgetRegistry);
```

## Activating It (Dependency Injection)

If your application uses `symfony/dependency-injection`, import both
package configuration files. `form-services.yaml` injects `InputActionResolver`
into its default element provider. `ElementRendererProviderInterface` combines
all tagged providers; its registry is injected into `FormRendererInterface`.
Register your own `Translator` to translate the action labels.
The configuration also decorates the form factory with
`TranslatingFormFactory`, which needs the application&#039;s `TranslatorInterface`. Register the translator under that interface:

```yaml
imports:
    - { resource: &#039;../vendor/derafu/data-processor/resources/config/data-processor-services.yaml&#039; }
    - { resource: &#039;../vendor/derafu/form/resources/config/form-services.yaml&#039; }

services:
    Symfony\Contracts\Translation\TranslatorInterface:
        class: Symfony\Component\Translation\Translator
        factory: [&#039;Derafu\Translation\TranslatorFactory&#039;, &#039;create&#039;]
        arguments:
            $defaultLocale: &#039;es&#039;
            $fallbackLocales: [&#039;es&#039;, &#039;en&#039;]
            $resourceProviders: !tagged_iterator derafu_translation.resource_provider
```

Both `DataProcessorTranslationResourceProvider` and
`FormTranslationResourceProvider` are already tagged
`derafu_translation.resource_provider` in their respective recipe files, so
they&#039;re picked up automatically. `FormDataProcessor` and
`InputActionResolver` both autowire `?TranslatorInterface`, so they resolve
to the interface registration above; neither needs explicit argument wiring.

## 4. Array Reading Errors

Form definitions and typed data readers use Derafu Array and Derafu Value for array/type validation. Failures from the readers, including `ProcessResult::getReader()` for a non-array result, follow the [Array exception contract](https://www.derafu.dev/docs/data/array/translations). Register Array&#039;s translation resource provider to translate those messages. Direct Value operations follow [Value&#039;s exception contract](https://www.derafu.dev/docs/data/value/translations).

These read failures are exceptions; they are not field validation errors added to `ProcessResult::getErrors()`. Form processing and the Data Processor translation setup described above retain their own contracts.




---

## CSRF Protection

The CSRF token of the forms, and the errors of a form as a whole

# CSRF Protection

A form is **protected with a CSRF token** unless it says otherwise. The form renders a hidden field `_token` with a token, and when its data is processed the token that comes back is checked. `derafu/form` does not know where tokens are kept, nor what a session or a request is: that is what a **CSRF token manager** knows, and the application gives one.

## The token manager

```php
namespace Derafu\Form\Contract\Csrf;

interface CsrfTokenManagerInterface
{
    // The token for an id (the form it is for).
    public function getToken(string $id): string;

    // Whether a token that came with a form is the one of the id for this user.
    public function isValid(string $id, string $token): bool;
}
```

The form asks for a token every time it is shown, and checks the one that comes with the data. How long a token lasts, and whether checking it uses it up, is up to each implementation.

The id is the **name of the schema** of the form, or `form` if it has none, so a token of one form is not good for another.

An implementation is specific to each environment, because it is the one that knows which session the tokens belong to (for example, one that wraps the token manager of Symfony, or one that works over the session of a Mezzio request). The package defines the contract and does not bring any.

## Wiring

With the services of the package (`form-services.yaml`) the manager is **optional**: if the application has a service that implements `CsrfTokenManagerInterface`, the renderer and the processor use it. When assembling services directly, inject it into the renderer and the processor:

```php
use Derafu\Form\Renderer\FormRenderer;

$renderer = new FormRenderer(
    $templateRenderer,
    $elementRendererRegistry,
    $widgetRendererRegistry,
    csrfTokenManager: $manager,
);

$processor = new FormDataProcessor($resolver, $dataProcessor, csrfTokenManager: $manager);
```

## A form that is protected needs a manager

Rendering or processing a form that is protected, **without a manager, is an error** (an exception with the name of the form), not a form that is silently left open. Either register a manager or turn the protection off for the form.

## Turning it off

It is an option of the form, which both the renderer and the processor read, so they always agree:

```yaml
# resources/forms/search.form.yaml
options:
    csrf_protection: false
```

A form that is not protected renders no token, and its data is processed without one. Use it for forms that do not need it, for example a search form with the method GET, or a form that is posted by clients that are not browsers.

## When the token is not valid

The token is **not part of the data**: it is taken out before the fields are processed. If it is missing, or it is not valid, the result is not valid and it has a message in the **errors of the form**:

```php
$result = $processor-&gt;process($form, $_POST);

$result-&gt;isValid();        // false
$result-&gt;getFormErrors();  // [&#039;The form is not valid or has expired. ...&#039;]
```

The fields are processed all the same, so their own errors come along. The message is translated if the processor has a translator (the text is in the domain `errors`).

## The errors of a form as a whole

Some errors do not belong to any field, like this one. They are in `ProcessResult::getFormErrors()`, they count in `hasErrors()` and they come first in `getAllErrors()`. The form that the result gives (`getForm()`) has them (`$form-&gt;getErrors()`), and the template of the form shows them **before its fields** with `form_global_errors(form)`:

```twig
{{ form_global_errors(form) }}
```

The errors of the fields are still shown in their rows, as before.




---

## Captcha

The captcha of the forms of derafu/form, with the provider of the application

# Captcha

A form can ask for a **captcha**: the form renders a widget, and when its data is processed what the visitor solved is checked. `derafu/form` does not know which captcha service it is, nor its keys: that is what a **captcha provider** knows, and the application gives one (for example the ones of [`derafu/captcha`](https://www.derafu.dev/docs/ui/captcha)).

## The option of the form

It is an option of the form, in the `options` of its definition, next to `csrf_protection` and `translation_domain`:

```yaml
# resources/forms/contact.form.yaml
options:
    captcha_protection: true
```

| Value | What happens |
| --- | --- |
| absent | The form is not protected with the captcha. Nothing is rendered or checked, even if the application has a provider. |
| `false` | The same, written down. |
| `true` | The form is **protected with the captcha**, always. With a provider available the widget is rendered and the data is checked, and the form is not valid if the visitor did not solve it, or if the service could not be asked (it fails closed). **If the application did not configure a captcha, it is an error**: the form can not be rendered nor processed, and the message says what to configure. |

A form is never left open because nobody thought of the captcha. A package that ships forms (a contact form, a login) declares `captcha_protection: true`, and the application configures a captcha once; no variable per form is needed. The simplest one needs no account: ALTCHA, with `CAPTCHA_PROVIDER=altcha` and a secret key (see [`derafu/captcha`](https://www.derafu.dev/docs/ui/captcha)).

The application can also decide, **on purpose**, not to have a captcha (`CAPTCHA_PROVIDER=none` in `derafu/captcha`): then the forms that are protected have none and there is no error. It is not the same as not configuring anything, which fails.

## The provider

```php
namespace Derafu\Form\Contract\Captcha;

interface CaptchaProviderInterface
{
    // Whether the application has configured a captcha.
    public function isAvailable(): bool;

    // Whether the application decided, on purpose, not to have one.
    public function isDisabled(): bool;

    // The name of the field that the widget writes in the form.
    public function getResponseField(): string;

    // The HTML of the widget, with its scripts.
    public function getWidget(string $formId): string;

    // Whether what the visitor solved is the proof of a person for that form.
    // It throws CaptchaUnavailableException if the service could not be asked.
    public function verify(string $token, string $formId): bool;
}
```

The id of the form is the name of its schema, or `form` if it has none (`$form-&gt;getId()`): the services that have an action (reCAPTCHA v3, Turnstile) use it, so what was solved for a form is not good for another.

## Rendering

`form_captcha(form)` renders the widget. `form.html.twig` and `renderBody` call it, after the fields and before the CSRF token, so a form that is rendered whole has it. A template that builds the form by hand writes it where it wants, before the button:

```twig
{{ form_start(form) }}
    {{ form_element(form.uiSchema, form) }}
    {{ form_captcha(form) }}
    {{ form_csrf(form) }}
    &lt;button type=&quot;submit&quot;&gt;Send&lt;/button&gt;
{{ form_end(form) }}
```

It renders nothing when the form is not protected with the captcha or the application disabled it on purpose.

## Processing

`FormDataProcessor` checks the captcha according to the option of the form, **never according to what arrives in the POST**: a request that is made by hand without the field is not valid.

- What the visitor solved is read from the raw data, in the field of the provider, and it is **not part of the processed data**.
- The service is asked last: after the CSRF token and after the fields, and only if they are valid, so it is not asked about a form that is not going to be accepted.
- When it is not valid, the result is not valid and has a message in the **errors of the form** (`getFormErrors()`). There are two messages: &quot;The captcha is not valid. Try again.&quot; and &quot;The captcha could not be verified. Try again in a moment.&quot; (the service did not answer). Both are translatable, in the domain `errors`.

## Wiring

With the services of the package (`form-services.yaml`) the provider is **optional**: if the application has a service that implements `CaptchaProviderInterface`, the renderer and the processor use it. Without one, the forms that are protected with the captcha fail. When assembling services directly, inject it into the renderer and the processor:

```php
use Derafu\Form\Renderer\FormRenderer;

$renderer = new FormRenderer(
    $templateRenderer,
    $elementRendererRegistry,
    $widgetRendererRegistry,
    captchaProvider: $provider,
);

$processor = new FormDataProcessor($resolver, $dataProcessor, captchaProvider: $provider);
```




---

## Validation

How the rules that process the data of a form are derived from its schema, and what each keyword of the schema validates

# Validation

`FormDataProcessor` processes the data that comes with a form: it casts, sanitizes, transforms and validates the value of each field, and gives back the processed data and the errors. The rules are the ones of [`derafu/data-processor`](https://www.derafu.dev/docs/data/data-processor). Nobody writes them for the common cases: they are **derived from the schema of the form**, and the `rules` section of the definition adds the rest.

```php
$result = $processor-&gt;process($form, $_POST);

if ($result-&gt;hasErrors()) {
    $errors = $result-&gt;getErrors();     // [&#039;field&#039; =&gt; [&#039;message&#039;]]
    $form = $result-&gt;getForm();         // The form with its errors, to render it again.
} else {
    $data = $result-&gt;getProcessedData();
}
```

## Typed Data Readers

`ProcessResultInterface::getReader()` returns a `Derafu\Array\ArrayReader` over the processed data. `getProcessedData()` continues to return the original value as `mixed`; requesting a reader requires that value to be an array, without converting its contents.

```php
$result = $processor-&gt;process($form, [&#039;contact&#039; =&gt; [&#039;address&#039; =&gt; &#039;Street 1&#039;]]);
$reader = $result-&gt;getReader();

$address = $reader-&gt;requireString(&#039;contact.address&#039;);
$zone = $reader-&gt;getString(&#039;contact.zone&#039;, &#039;North&#039;);
```

The reader is also available on `FormDataInterface`. It is a snapshot: obtain another reader after changing FormData. Objects stored inside the array retain their identity.

```php
use Derafu\Form\Data\FormData;

$data = new FormData([&#039;contact&#039; =&gt; [&#039;address&#039; =&gt; &#039;Street 1&#039;]]);
$before = $data-&gt;getReader();
$data-&gt;set(&#039;contact.address&#039;, &#039;Street 2&#039;);

$before-&gt;requireString(&#039;contact.address&#039;);           // &#039;Street 1&#039;
$data-&gt;getReader()-&gt;requireString(&#039;contact.address&#039;); // &#039;Street 2&#039;
```

Reader keys use literal-key precedence and dot notation, including numeric positions. JSON Forms scopes such as `#/properties/contact/properties/address` belong to FormData&#039;s existing `get()`, `has()` and `set()` methods; use `contact.address` with the reader.

Strict getters preserve existing types; explicit conversions use `getAsXXX()` / `requireAsXXX()`. Missing or null values return an optional getter&#039;s default and fail a required read. The reader does not run form processing rules or change the processing result&#039;s validity or errors. See [Array Readers](https://www.derafu.dev/docs/data/array/readers) and [Value Types](https://www.derafu.dev/docs/data/value/types).

## Where the rules come from

For each field the processor joins three sources, in this order:

1. **The property of the schema**: its `type`, `format`, `pattern`, limits, `enum`, etc. (see below).
2. **The control of the UI schema**: a control of type `file` or `image` validates a file or an image (see [Files](#files)), a control of type `editor` removes the tags of the HTML, and a control of type `ipv4`, `ipv6`, `hostname`, `uuid`, `url`, `time`, `color`, `month` or `week` validates that format.
3. **The `rules` section of the definition**: explicit rules by field.

```php
&#039;rules&#039; =&gt; [
    &#039;name&#039; =&gt; [
        &#039;transform&#039; =&gt; [&#039;uppercase&#039;],
        &#039;validate&#039; =&gt; [&#039;min_length:3&#039;],
    ],
],
```

The rules of a field are written in four categories, and are applied in this order: `cast`, `transform`, `sanitize`, `validate`. The explicit ones are joined to the derived ones like this:

- `cast`: the explicit one **replaces** the derived one. When the type of the cast changes, the derived sanitizers (for example `trim`, that is for strings) are dropped, and the explicit ones are kept.
- `sanitize`, `transform` and `validate`: the explicit ones are **added after** the derived ones.
- `required`: the fields that are required (see [Required fields](required-fields)) have it as the first rule of `validate`, once.

A field whose [rule of the UI schema](examples/rules) is not active (it is hidden, for example) is not validated and is not in the processed data, even if it came with the data.

## Objects

The properties of an object of the schema are fields of the form with the name of their path, `address.city`, and the data has them inside the object, as PHP reads a form (`address[city]` in the name of the control):

```php
&#039;schema&#039; =&gt; [
    &#039;type&#039; =&gt; &#039;object&#039;,
    &#039;required&#039; =&gt; [&#039;contact&#039;],
    &#039;properties&#039; =&gt; [
        &#039;contact&#039; =&gt; [
            &#039;type&#039; =&gt; &#039;object&#039;,
            &#039;required&#039; =&gt; [&#039;address&#039;, &#039;zone&#039;],
            &#039;properties&#039; =&gt; [
                &#039;address&#039; =&gt; [&#039;type&#039; =&gt; &#039;string&#039;],
                &#039;zone&#039; =&gt; [&#039;type&#039; =&gt; &#039;string&#039;],
                &#039;city&#039; =&gt; [&#039;type&#039; =&gt; &#039;string&#039;],
            ],
        ],
    ],
],
&#039;uischema&#039; =&gt; [
    &#039;type&#039; =&gt; &#039;VerticalLayout&#039;,
    &#039;elements&#039; =&gt; [
        [&#039;type&#039; =&gt; &#039;Control&#039;, &#039;scope&#039; =&gt; &#039;#/properties/contact/properties/address&#039;],
        [&#039;type&#039; =&gt; &#039;Control&#039;, &#039;scope&#039; =&gt; &#039;#/properties/contact/properties/zone&#039;],
        [&#039;type&#039; =&gt; &#039;Control&#039;, &#039;scope&#039; =&gt; &#039;#/properties/contact/properties/city&#039;],
    ],
],
```

```php
$result = $processor-&gt;process($form, [&#039;contact&#039; =&gt; [&#039;address&#039; =&gt; &#039;Street 1&#039;, &#039;zone&#039; =&gt; &#039;North&#039;, &#039;city&#039; =&gt; &#039;&#039;]]);

$result-&gt;getProcessedData();  // [&#039;contact&#039; =&gt; [&#039;address&#039; =&gt; &#039;Street 1&#039;, &#039;zone&#039; =&gt; &#039;North&#039;, &#039;city&#039; =&gt; &#039;&#039;]]
$result-&gt;getErrors();         // [&#039;contact.zone&#039; =&gt; [...]] when the zone is missing.
```

- The processed data and the data that comes back to the form have the same shape as the data that came.
- The errors have the name of the path of the field (`contact.zone`).
- A field is required by the `required` of **its own object**: `address` and `zone` are, `city` is not. The `required` of the root only asks for the key `contact`: it does not make any of its fields required.
- A key with the whole name (`&#039;contact.address&#039;`) is the value of that field too.
- The conditions of the [rules of the UI schema](examples/rules) can be on a field of an object (`#/properties/contact/properties/city`).

### Fields that are not in the schema

The form is closed: what comes with the data and is not a field of the form is **not** in the processed data. It is not an error, because a browser can send fields that are not of the form (the button that submitted it, for example). The `additionalProperties` of an object opens it:

| `additionalProperties` of the object | The fields of the data that are not in the form |
|---|---|
| absent, or `false` | are dropped |
| `true`, or a schema | are kept in the object as they came, without validating them |

Each object decides for itself, the root included:

```php
&#039;schema&#039; =&gt; [
    &#039;type&#039; =&gt; &#039;object&#039;,
    &#039;properties&#039; =&gt; [
        &#039;name&#039; =&gt; [&#039;type&#039; =&gt; &#039;string&#039;],
        &#039;contact&#039; =&gt; [
            &#039;type&#039; =&gt; &#039;object&#039;,
            &#039;additionalProperties&#039; =&gt; true,
            &#039;properties&#039; =&gt; [&#039;address&#039; =&gt; [&#039;type&#039; =&gt; &#039;string&#039;]],
        ],
    ],
],
```

```php
$result = $processor-&gt;process($form, [&#039;name&#039; =&gt; &#039;Ana&#039;, &#039;extra&#039; =&gt; &#039;x&#039;, &#039;contact&#039; =&gt; [&#039;address&#039; =&gt; &#039;Street 1&#039;, &#039;zip&#039; =&gt; &#039;123&#039;]]);

$result-&gt;getProcessedData();  // [&#039;name&#039; =&gt; &#039;Ana&#039;, &#039;contact&#039; =&gt; [&#039;address&#039; =&gt; &#039;Street 1&#039;, &#039;zip&#039; =&gt; &#039;123&#039;]]
```

`extra` is dropped because the root is closed, and `zip` is kept because `contact` is open. The CSRF token and the response of the captcha are never in the processed data, and neither is a field that is not active.

### Fields that depend on another

`dependentRequired` makes some fields of an object required when another one has a value:

```php
&#039;contact&#039; =&gt; [
    &#039;type&#039; =&gt; &#039;object&#039;,
    &#039;dependentRequired&#039; =&gt; [&#039;card&#039; =&gt; [&#039;address&#039;, &#039;zip&#039;]],
    &#039;properties&#039; =&gt; [
        &#039;card&#039; =&gt; [&#039;type&#039; =&gt; &#039;string&#039;],
        &#039;address&#039; =&gt; [&#039;type&#039; =&gt; &#039;string&#039;],
        &#039;zip&#039; =&gt; [&#039;type&#039; =&gt; &#039;string&#039;],
    ],
],
```

```php
$result = $processor-&gt;process($form, [&#039;contact&#039; =&gt; [&#039;card&#039; =&gt; &#039;4111&#039;, &#039;address&#039; =&gt; &#039;&#039;, &#039;zip&#039; =&gt; &#039;&#039;]]);

$result-&gt;getErrors();  // [&#039;contact.address&#039; =&gt; [&#039;Field is required.&#039;], &#039;contact.zip&#039; =&gt; [&#039;Field is required.&#039;]]
```

- A field has a value when it is not `null`, `&#039;&#039;` or `[]`, as `required` reads it. The exception is the field that triggers: a checkbox that is not checked (`false`) is not a value, so &quot;if it asks for an invoice, the tax id is required&quot; does not ask for it when the box is empty.
- The error is the one of `required`, in the path of each field that is missing.
- The names are the ones of the object: in `contact`, `card` is `contact.card`. A name that is not a field of the form, or a field that is not active, is not required and does not trigger.

`minProperties` and `maxProperties` are not derived: the properties of an object are the fields of the schema, so their number does not depend on what the visitor sends.

## What the schema validates

| In the schema | Rule |
|---|---|
| `type: string` | cast `string`; sanitize `trim` |
| `type: integer` | cast `integer`; validate `int` |
| `type: number` | cast `float`; validate `numeric` |
| `type: boolean` | cast `boolean` |
| `minLength`, `maxLength` | `min_length`, `max_length` |
| `minimum`, `maximum` (integer and number) | `gte`, `lte` |
| `exclusiveMinimum`, `exclusiveMaximum`, `multipleOf` (integer and number) | `gt`, `lt`, `multiple_of` |
| `minItems`, `maxItems`, `uniqueItems` | `min_items`, `max_items`, `unique` |
| `contains`, `minContains`, `maxContains` | `contains`, `min_contains`, `max_contains` (see [Arrays](#arrays)) |
| `pattern` | `regex` (see below) |
| `enum`, `const`, or `oneOf` with `const` | `in` with the values |
| `items` with `enum` or `oneOf` (a multiple selection) | `in` with the values: each element must be one of them |
| `contentMediaType: application/json` | `json` |
| `format` | see the table below |

A string is trimmed, except the one of a control of type `password` or with `format: password`: the spaces at its ends are part of it. A string with `format: email` is also transformed to lowercase.

The values of `in` are compared as text, and a comma that is in a value is escaped (`\,`) so it does not split it.

### Formats

| `format` | Rule |
|---|---|
| `email` | `email` |
| `uri`, `url` | `url` |
| `date` | `date_format:Y-m-d` |
| `date-time` | `datetime_local`: `YYYY-MM-DDTHH:MM[:SS]`, as `&lt;input type=&quot;datetime-local&quot;&gt;` sends it |
| `time` | `time`: `HH:MM[:SS]` |
| `color` | `color`: `#rrggbb` |
| `month` | `month`: `YYYY-MM` |
| `week` | `week`: `YYYY-Www` |
| `tel` | `regex` of telephone numbers |
| `hostname` | `hostname` |
| `ipv4`, `ipv6` | `ip:v4`, `ip:v6` |
| `uuid` | `uuid` |
| `base64` | `base64` |
| `json` | `json` |
| `regex` | `regex_pattern`: the value must be a regular expression |
| another | no rule: it only changes the control that is drawn |

### Patterns

The `pattern` of JSON Schema is written without delimiters, like the browsers read the `pattern` attribute of HTML. PHP needs them, so the form gives the pattern the slash as its delimiter and escapes the slashes that it has, once: `^a/b$` and `^a\/b$` are the same pattern. The same conversion is used by the patterns of the types and by the conditions of the rules of the UI schema.

The regular expression is a PCRE one, the dialect of PHP. A pattern that can not be compiled is an error of the definition, not of the value: it is reported when the field is processed. A field with `format: regex` is the opposite: the **value** is the pattern, and it is invalid if it can not be compiled.

### Booleans

For JSON Schema, `required` says that the key must be in the data, not that it has a given value. A boolean that is only `required` is valid when it is checked and when it is not. To ask for a value, fix it in the schema:

```php
&#039;terms&#039; =&gt; [
    &#039;type&#039; =&gt; &#039;boolean&#039;,
    &#039;title&#039; =&gt; &#039;I accept the terms&#039;,
    &#039;const&#039; =&gt; true,          // or &#039;enum&#039; =&gt; [true]
],
```

- `const: true` or `enum: [true]` validate with `accepted`: the value must be `true`.
- `const: false` or `enum: [false]` validate with `declined`: the value must be `false`.

A browser does not send a checkbox that is not checked, so a missing key is read as `false`, and the form that asks for `true` fails. The control has the native `required` too, see [Required fields](required-fields).

### Arrays

`contains` is derived only when its schema is a `const` or an `enum`, because the rules compare the elements with a list of values:

| In the schema | Rule |
|---|---|
| `contains: {const: &#039;terms&#039;}` | `contains:terms` |
| `contains: {enum: [&#039;a&#039;, &#039;b&#039;]}` | `contains:a,b` |
| `contains` and `minContains: 2` | `min_contains:2,a,b` |
| `contains` and `minContains: 0` | no rule for the minimum |
| `contains` and `maxContains: 3` | `max_contains:3,a,b` |

Without `minContains`, at least one element must be one of the values. The elements are compared as text, as `in` does. `minContains` and `maxContains` without `contains` are ignored, and so is a `contains` with another schema, or with values that the rules never match (a boolean, `null`, an array, an empty text).

### Files

A control of type `file` or `image` has only the rules of the file: its value is an upload, so it is not cast or sanitized. The options of the control are:

- `max_size` and `min_size`: a number of bytes, or a size with a unit (`2M`, `1.5Mi`).
- `accept`: the extensions (`.pdf`) and the types (`application/pdf`, `image/*`) that are accepted. The file is checked by its **content**, not by its name or by what the browser says. The types of an explicit `mimetype` rule are joined with the ones of `accept`.

## Read-only fields

A property with `readOnly: true` is not taken from what came with the data. Its value is the one that the form has, the same that was drawn: the data of the form or, if it has none, the `default` of the schema, and `null` if there is neither. No rule is applied to it, so a `required` read-only field without a value is not an error.

```php
// The form has the data [&#039;code&#039; =&gt; &#039;A-1&#039;], and `code` is read-only.
$result = $processor-&gt;process($form, [&#039;code&#039; =&gt; &#039;HACK&#039;]);

$result-&gt;getProcessedData();  // [&#039;code&#039; =&gt; &#039;A-1&#039;]
```

The rules of the UI schema that depend on the field read the value of the form too, so what the visitor sends can not change them.

## Translated errors

The messages of the errors are translated when the processor has a translator, see [Translations](translations).




---

## Required Fields

How a field is required, how its label and its control say it, and how the browser asks for it

# Required Fields

A field is **required** when its property is in the `required` list of the object that has it, as in JSON Schema:

```php
&#039;schema&#039; =&gt; [
    &#039;type&#039; =&gt; &#039;object&#039;,
    &#039;required&#039; =&gt; [&#039;name&#039;, &#039;email&#039;],
    &#039;properties&#039; =&gt; [
        &#039;name&#039; =&gt; [&#039;type&#039; =&gt; &#039;string&#039;],
        &#039;email&#039; =&gt; [&#039;type&#039; =&gt; &#039;string&#039;, &#039;format&#039; =&gt; &#039;email&#039;],
        &#039;nick&#039; =&gt; [&#039;type&#039; =&gt; &#039;string&#039;],
    ],
],
```

The form marks each of its fields (`$field-&gt;isRequired()`), and three things use it:

- The **processor** validates the value with the rule `required` before any other (see [Validation](validation)).
- The **label** shows the marker of a required field.
- The **control** says that it is required to the browser and to the assistive technologies.

## The marker of the label

The label of a required field has the class `required` and an asterisk (`&lt;span class=&quot;text-danger&quot;&gt;*&lt;/span&gt;`). It is shown unless the option `hide_required_asterisk` is `true`:

```php
// In the options of the form: all of its fields.
&#039;options&#039; =&gt; [&#039;hide_required_asterisk&#039; =&gt; true],

// In a control: only that field.
[&#039;type&#039; =&gt; &#039;Control&#039;, &#039;scope&#039; =&gt; &#039;#/properties/name&#039;, &#039;options&#039; =&gt; [&#039;hide_required_asterisk&#039; =&gt; true]],
```

It can also be given when rendering (`{{ form_row(field, {hide_required_asterisk: true}) }}`). The option of the control decides first, then the ones that are given when rendering and last the ones of the form (see [Rendering options](rendering-options)). A value that is not a boolean is an error.

## What the browser asks for

By default the control of a required field has the **native `required`**, so the browser does not send the form until it has a value:

| Control | Attribute |
|---|---|
| Input (except `hidden`), textarea, select | `required` |
| Radio buttons | `required` in the first one (it is enough for the group), and `aria-required=&quot;true&quot;` in the group (`role=&quot;radiogroup&quot;`) |
| Group of checkboxes | `aria-required=&quot;true&quot;` in the group (`role=&quot;group&quot;`): a browser can not ask for one of several |
| Slider | none: it always has a value |

The form can say that the browser does not ask for it, with the option `native_required`:

```php
&#039;options&#039; =&gt; [&#039;native_required&#039; =&gt; false],
```

Then the controls only have `aria-required=&quot;true&quot;` (the assistive technologies say that the field is required, and the browser lets the form go). `native_required` is read like `hide_required_asterisk`: from the control, from what is given when rendering, from the form.

When the form does not say it, `native_required` is the opposite of `novalidate`: a form with the attribute `novalidate` (`&#039;options&#039; =&gt; [&#039;attributes&#039; =&gt; [&#039;novalidate&#039; =&gt; true]]`) is not validated by the browser, so it does not ask for the required fields either. An explicit `native_required: true` wins over `novalidate`.

The widgets and the labels that are rendered alone (`form_widget(field)`, `form_label(field)`) have the same behavior as the ones inside a form: it is the field that carries what its form decided.

```php
$field-&gt;isRequired();                 // It is in the `required` list.
$field-&gt;isNativeRequired();           // Its control has the native `required`.
$field-&gt;isRequiredAsteriskHidden();   // Its label does not show the asterisk.
```

### Booleans

`required` says that the key must be in the data, not that it has a value, so a boolean that is only required has no marker and no `required` in its control. To ask for `true` (to accept the terms of a service) the schema says it:

```php
&#039;terms&#039; =&gt; [
    &#039;type&#039; =&gt; &#039;boolean&#039;,
    &#039;title&#039; =&gt; &#039;I accept the terms&#039;,
    &#039;const&#039; =&gt; true,        // or &#039;enum&#039; =&gt; [true]
],
```

Its checkbox always has the native `required` and its label the asterisk, and the processor validates it with `accepted` (see [Validation](validation)).

## Fields that are not always there

A field with a [rule of the UI schema](examples/rules) that is not active when the form is rendered (it is hidden, or it is not enabled) has its controls `disabled`: the browser does not validate them nor sends them. When the data of the form changes, `ui-schema-rules.js` disables and enables them again as the rule says.

The processor does not validate the field that is not active either, even if its value came.

## Tabs and sections that are closed

A browser validates the controls that are in a tab that is not active or in a section that is collapsed, but it can not focus them: it blocks the form and shows nothing. `invalid-reveal.js` solves it. When the form is invalid, it opens the tabs and the sections that have the first invalid control, focuses it and shows the message of the browser. It uses Bootstrap 5, the same that the templates of the categorizations and of the groups use.

```js
import { InvalidReveal } from &#039;derafu-form/invalid-reveal.js&#039;;

document.addEventListener(&#039;DOMContentLoaded&#039;, () =&gt; InvalidReveal.init());
```

(With the Symfony bundle the module is in the import map under `derafu-form/`; without it, import it from `vendor/derafu/form/resources/js/invalid-reveal.js`.) If the control is already visible, the script does nothing.

## Editors

The JSON editor (`json-editor.js`) and the HTML editor (`html-editor.js`) hide the control that they replace. A hidden control can not be focused, so both remove its `required`; the processor still asks for the value.

### Setting the content of the JSON editor from code

`json-editor.js` exports two functions to work with the editor that replaces a control, given the control itself:

```js
import { getJsonEditor, setJsonEditorValue } from &#039;derafu-form/json-editor.js&#039;;

const field = document.querySelector(&#039;[name=&quot;documents&quot;]&#039;);

// Replace the content of the editor.
setJsonEditorValue(field, [{ name: &#039;Example&#039; }]);

// The JSONEditor instance, to use any of its methods (undefined without editor).
const editor = getJsonEditor(field);
```

`setJsonEditorValue()` also updates the control, which is what the form submits: the editor does not notify the changes that are made by code. It throws an `Error` if the control has no editor.




---

## Rendering Options

Where the options of an element come from, which one decides, and the options of the layouts, the groups and the columns

# Rendering Options

The way an element is rendered depends on its **options**, and they can be given in several places. The one that is closest to the element decides.

## Which option decides

From the one that decides first to the one that decides last:

1. **The options of the element**: the `options` of its definition in the UI schema.
2. **The options that are given when rendering**: the second argument of the Twig functions (`form(form, options)`, `form_row(field, options)`, `form_element(element, form, options)`...) or the `$options` of the renderer. They go down to all the elements, so they are the defaults of the whole tree.
3. **The options of the form**: the `options` section of its definition.
4. **The defaults of the renderer.**

```php
&#039;options&#039; =&gt; [&#039;floating_labels&#039; =&gt; false],           // 3. All the fields.
```

```twig
{{ form(form, {floating_labels: true}) }}             {# 2. Overrides the form. #}
```

```php
[&#039;type&#039; =&gt; &#039;Control&#039;, &#039;scope&#039; =&gt; &#039;#/properties/name&#039;, &#039;options&#039; =&gt; [&#039;floating_labels&#039; =&gt; false]],  // 1. Wins.
```

The options of a layout, of a group or of a categorization are for itself: its children do not get them.

## Options of the layouts

| Element | Option | What it does |
|---|---|---|
| `VerticalLayout` | `layout_attr` | Attributes of its container (`class`, `id`, `data-*`...) |
| `HorizontalLayout` | `layout_attr` | Attributes of its row |
| `Group` | `group_attr` | Attributes of its card |
| `Group` | `collapsible` | The group can be collapsed |
| `Group` | `collapsed` | It starts collapsed |
| `Group` | `footer` | HTML of the footer of the card |
| `Categorization` | `categorization_attr` | Attributes of its container |
| `Categorization` | `tab_style` | `horizontal` (by default) or `vertical` |
| `Categorization` | `vertical_col_width` | Columns of the tabs when they are vertical (3 by default) |
| `Category` | `category_attr` | Attributes of the content of the tab |

```php
[
    &#039;type&#039; =&gt; &#039;Group&#039;,
    &#039;label&#039; =&gt; &#039;Address&#039;,
    &#039;options&#039; =&gt; [&#039;collapsible&#039; =&gt; true, &#039;collapsed&#039; =&gt; true, &#039;footer&#039; =&gt; &#039;We never share it.&#039;],
    &#039;elements&#039; =&gt; [/* ... */],
],
```

## Columns of a horizontal layout

The elements of a `HorizontalLayout` are columns of the row. The ones that do not say their size share what is left, **in equal parts**, so with any number of elements the row is full. An element asks for a size with `col_size`, the number of columns of Bootstrap (from 1 to 12, or `auto`):

```php
[
    &#039;type&#039; =&gt; &#039;HorizontalLayout&#039;,
    &#039;elements&#039; =&gt; [
        [&#039;type&#039; =&gt; &#039;Control&#039;, &#039;scope&#039; =&gt; &#039;#/properties/street&#039;, &#039;options&#039; =&gt; [&#039;col_size&#039; =&gt; 8]],
        [&#039;type&#039; =&gt; &#039;Control&#039;, &#039;scope&#039; =&gt; &#039;#/properties/number&#039;],   // The rest: 4.
    ],
],
```

The class of the column is `col-md-8` for the first one and `col-md` for the second.

## Options for the children of a layout

A layout or a group can give options to each one of its children by its position, with `elements_options`: a list where the entry `n` is for the child `n`. They count as options that are given to that child when rendering, so the options of the child itself decide before them (see above).

```php
[
    &#039;type&#039; =&gt; &#039;Group&#039;,
    &#039;label&#039; =&gt; &#039;Address&#039;,
    &#039;options&#039; =&gt; [
        &#039;elements_options&#039; =&gt; [
            [&#039;attr&#039; =&gt; [&#039;autocomplete&#039; =&gt; &#039;street-address&#039;]],   // For the first child.
            [],                                                 // The second one has none.
        ],
    ],
    &#039;elements&#039; =&gt; [/* ... */],
],
```

In a `HorizontalLayout` the entry of a child is also the one of its **column**: its `col_size` and its `class` are taken from it, and they decide before the `col_size` that the child asks for.

```php
&#039;options&#039; =&gt; [&#039;elements_options&#039; =&gt; [[&#039;col_size&#039; =&gt; 3, &#039;class&#039; =&gt; &#039;text-end&#039;], []]],
```

## The end of the form

`form_end` renders the closing tag, and before it the fields that were not rendered yet (`form_rest`), with the same options as the rest of the form. The option `render_rest` set to `false` does not render them:

```twig
{{ form_start(form) }}
    {{ form_row(form.fields.name) }}
{{ form_end(form, {render_rest: false}) }}
```




---

## Examples

Examples of how to use the form component.

# Form Examples




---

### From Data

The simplest form, created from data only.






---

### Control

The default controls provided by the form library.






---

### User Registration

Form to create a new user account.






---

### User Login

A user login form with username, password and 2FA options.






---

### User Profile with Cards

User profile form with grouped sections in cards.






---

### User Profile with Tabs

User profile form with tabs and cards.






---

### Setup Wizard

Multi-step wizard for account setup.






---

### Invoice Issuance

Form for creating invoices with basic fields and line items.






---

### Advanced Invoice Search

Complex search form for filtering invoices with conditional fields.






---

### E-Invoicing Configuration

Comprehensive configuration form for electronic invoicing.






---

### Contact Form

Simple contact form with default values and validation.






---

### User Registration

Complex user registration form with nested fields and validation.






---

### Collection

Collections and arrays in forms.






---

### Editors

Different editors using controls.






---

### Product Ecommerce

Product creation form with data processing rules.






---

### Rules

JSON Forms rules in UI Schema.






---

### Cascade

Select options in a cascade.






---

## Service Configuration

Form rendering services, isolated Twig and tagged contributions

# Service Configuration

Import the production configurations and provide your application&#039;s translator.
The translator receives the catalogues contributed by the imported packages:

```yaml
imports:
    - { resource: &#039;../vendor/derafu/data-processor/resources/config/data-processor-services.yaml&#039; }
    - { resource: &#039;../vendor/derafu/form/resources/config/form-services.yaml&#039; }

services:
    Symfony\Contracts\Translation\TranslatorInterface:
        class: Symfony\Component\Translation\Translator
        factory: [&#039;Derafu\Translation\TranslatorFactory&#039;, &#039;create&#039;]
        arguments:
            $defaultLocale: en
            $fallbackLocales: [en]
            $resourceProviders: !tagged_iterator derafu_translation.resource_provider
```

Inject `FormFactoryInterface`, `FormRendererInterface` and
`FormDataProcessorInterface` into your application services. The factory creates
forms from definitions; the renderer and processor share the configured types,
rule evaluator and optional CSRF/captcha integrations.

## Isolated Rendering

Form rendering owns qualified services such as
`Derafu\Twig\Contract\TwigServiceInterface $form` and
`Derafu\Renderer\Contract\RendererInterface $form`. Importing Form does not
replace the application&#039;s Twig or Renderer services. The internal
`FormTwigExtension` is loaded only in the form environment. A host framework can
register the same extension in its own page environment, with or without a
prefix on the function names. The
[Symfony Form Bundle](https://www.derafu.dev/docs/symfony/form-bundle#coexistence-with-symfony-form)
registers it without a prefix and chooses between the Derafu and the Symfony
functions by the type of the first argument.

The package&#039;s template directory is contributed automatically. Scalar Twig
options belong to `derafu.form.twig.options`, for example `{ extra: false }`.
`derafu.form.twig.component_registrar.cache_key` identifies the form-specific
component configuration when a PSR cache pool is provided.

## Contributions

Each domain supplies only its own providers. The following tags belong to the
form environment:

| Tag | Provider contract | Contribution |
| --- | --- | --- |
| `derafu_form.element_renderer_provider` | `ElementRendererProviderInterface` | Element type to renderer map |
| `derafu_form.widget_renderer_provider` | `WidgetRendererProviderInterface` | Widget type to renderer map |
| `derafu_form.twig.template_path_provider` | `Derafu\Twig\Contract\TemplatePathProviderInterface` | Template directories |
| `derafu_form.twig.extension_provider` | `Derafu\Twig\Contract\ExtensionProviderInterface` | Twig extensions |
| `derafu_form.twig.component_provider` | `Derafu\Twig\Contract\ComponentProviderInterface` | Twig component classes |
| `derafu_form.formatter_handler_provider` | `Derafu\Renderer\Contract\FormatterHandlerProviderInterface` | Named formatter handlers |
| `derafu_form.renderer.engine` | `Derafu\Renderer\Contract\EngineInterface` | Rendering engines |

Individual component classes can also use `derafu_form.twig.component`.
Providers are processed by descending tag priority. The first contribution for
an element/widget type wins. Default element/widget providers and the package&#039;s
template-path provider have priority `-1000`, so ordinary consumer providers
can override their own entries without copying the defaults. Twig retains its
first extension of each class; template directories are searched in priority
order. Formatter providers use the first handler of each name.

```yaml
services:
    App\Form\TemplatePathProvider:
        tags: [&#039;derafu_form.twig.template_path_provider&#039;]

    App\Form\WidgetRendererProvider:
        tags:
            - { name: derafu_form.widget_renderer_provider, priority: 100 }
```

Registries remain injectable through `ElementRendererRegistryInterface` and
`WidgetRendererRegistryInterface`. Rendering extensions are resolved when Twig
creates its environment, allowing the internal form functions to call the same
form renderer without eager construction cycles.





---
Last updated on 09/11/2026
#php
