Skip to content

Caelrik\Ui\Components\Form ​

Field ​

final class Caelrik\Ui\Components\Form\Field

A Bootstrap form control with validation rules.

Rules are emitted as native HTML5 attributes (required, minlength, pattern...), which Parsley.js reads on the client and browsers understand without JavaScript.

Constants ​

ConstantValue
REQUIRED_MARKER' <span class="caelrik-required" aria-hidden="true">*</span>'
SIGNATURE_LABELS['draw' => 'Draw your signature with a mouse, a finger or a pen, or type your name.', 'type' => 'Type your name', 'clear' => 'Clear the signature', 'empty' =…
MARKDOWN_LABELS['toolbar' => 'Formatting', 'bold' => 'Bold', 'italic' => 'Italic', 'heading' => 'Heading', 'link' => 'Link', 'bulletList' => 'Bulleted list', 'numberedList'…
IMAGE_EDITOR_LABELS['editor' => 'Edit the picture', 'rotateLeft' => 'Rotate left', 'rotateRight' => 'Rotate right', 'flipHorizontal' => 'Flip horizontally', 'flipVertical' => '…
CODE_LANGUAGES['text', 'javascript', 'typescript', 'jsx', 'php', 'html', 'css', 'json', 'sql', 'python', 'markdown', 'xml']
CODE_LABELS['keys' => 'Tab moves to the next field; Ctrl+] indents and Ctrl+[ outdents.', 'tabKeys' => 'Tab indents; press Escape, then Tab, to leave the editor.']
SIGNATURE_MAX_BYTES512000
PAIR_PLACEHOLDER'__pair__'

Methods ​

input ​

php
static input(string $type, string $name, ?string $label = null): self

text ​

php
static text(string $name, ?string $label = null): self

email ​

php
static email(string $name, ?string $label = null): self

password ​

php
static password(string $name, ?string $label = null): self

number ​

php
static number(string $name, ?string $label = null): self

tel ​

php
static tel(string $name, ?string $label = null): self

date ​

php
static date(string $name, ?string $label = null): self

A date (YYYY-MM-DD), with the browser's date picker.

time ​

php
static time(string $name, ?string $label = null): self

A time (HH:MM, or HH:MM:SS with a step under 60), with the browser's time picker.

datetime ​

php
static datetime(string $name, ?string $label = null): self

A local date and time (YYYY-MM-DDTHH:MM), with the browser's picker. It has no time zone: convert it on the server with the user's time zone.

dateRange ​

php
static dateRange(string $name, ?string $label = null, string $type = 'date'): self

A start and an end, in a fieldset: two native inputs that submit name[start] and name[end]. The end must be on or after the start. min(), max() and step() apply to both; value() takes ['start' => …, 'end' => …].

  • $type: "date", "time" or "datetime-local"

labels ​

php
labels(string $start, string $end): self

Labels of the two inputs of a dateRange() field (default "From" and "To").

hidden ​

php
static hidden(string $name, string|int|float $value): self

textarea ​

php
static textarea(string $name, ?string $label = null): self

select ​

php
static select(string $name, array $choices, ?string $label = null): self

tags ​

php
static tags(string $name, array $suggestions = [], ?string $label = null): self

Free-text tags: the user types a tag and presses Enter or a comma, or picks one of the suggestions (Tom Select). Submits name[]; value() takes a list of strings. Without JavaScript, it is a multiple select of the suggestions and current tags.

  • $suggestions: Tags offered as the user types.

minTags ​

php
minTags(int $min): self

The fewest tags of a tags() field. It makes the field required: required() alone is minTags(1).

maxTags ​

php
maxTags(int $max): self

The most tags of a tags() field: the user cannot add more.

addText ​

php
addText(string $text): self

The text offering a new tag in the list, %s being what the user typed (default "Add %s").

rating ​

php
static rating(string $name, ?string $label = null): self

A star rating: radio buttons shown as stars, in a fieldset with the label as its legend. Submits a whole number from 1 to stars(), or "" for "No rating" when the field is not required.

stars ​

php
stars(int $count): self

How many stars a rating() field has (3 to 10, default 5).

ratingLabels ​

php
ratingLabels(?string $star = null, ?string $clear = null): self

Texts of a rating() field, for translation: each star's name, with the value and the number of stars (default "%d of %d"), and the choice that clears the rating when the field is not required (default "No rating").

otp ​

php
static otp(string $name, ?string $label = null): self

A one-time code (a code sent by SMS or e-mail, or from an authenticator app): one input, shown as a box per character. The browser and phones offer the code received (autocomplete="one-time-code"), and pasting works. Digits only, 6 by default. Its error message is "Enter the 6-digit code."; message() replaces it.

codeLength ​

php
codeLength(int $length): self

How many characters a one-time code has (4 to 10, default 6).

alphanumeric ​

php
alphanumeric(bool $alphanumeric = true): self

A one-time code of letters and digits, e.g. K7M2QX, instead of digits only.

keyValue ​

php
static keyValue(string $name, ?string $label = null): self

A list of key-value pairs (metadata, HTTP headers, settings): a row per pair, with Add and Remove buttons. Each row submits as name[n][key] and name[n][value]; Field::keyValues() turns the submitted rows into a key => value array. value() takes such an array. A value needs a key, and a key is used once.

keySuggestions ​

php
keySuggestions(array $keys): self

Keys the key inputs suggest as the user types (a datalist), e.g. common HTTP headers. Other keys are accepted.

keyValueLabels ​

php
keyValueLabels(?string $key = null, ?string $value = null, ?string $add = null, ?string $remove = null, ?string $missing = null, ?string $duplicate = null): self

The texts of a key-value list: the column names (each input is named "Key 2", "Value 2" for assistive technology), the buttons (remove takes the row's position) and the messages for a value without a key and for a key used twice.

keyValues ​

php
static keyValues(mixed $rows): array

The submitted rows of a key-value list as a key => value array. Keys are trimmed; rows without a key are left out; a key used twice keeps its last value.

checkbox ​

php
static checkbox(string $name, ?string $label = null): self

switch ​

php
static switch(string $name, ?string $label = null): self

On/off switch: a checkbox shown as a toggle, announced as a switch. Submits "1" when on.

radio ​

php
static radio(string $name, array $choices, ?string $label = null): self

Radio buttons in a fieldset, the label as its legend. required() requires a choice.

checkboxes ​

php
static checkboxes(string $name, array $choices, ?string $label = null): self

Checkboxes in a fieldset, the label as its legend. Submits the checked values as an array (name[]); value() takes an array. required() requires at least one.

range ​

php
static range(string $name, ?string $label = null): self

Slider (min 0, max 100 and step 1 unless set). The current value is shown next to the label.

color ​

php
static color(string $name, ?string $label = null): self

Color picker. Submits a lowercase hex color such as #0d6efd.

file ​

php
static file(string $name, ?string $label = null): self

File upload. Without upload() it is a plain file input (the form switches to multipart); with upload() FilePond sends each file to that endpoint first.

editor ​

php
static editor(string $name, ?string $label = null): self

Rich text editor (Quill). Submits HTML: always sanitize it on the server (see EditorHtml::sanitize()).

markdown ​

php
static markdown(string $name, ?string $label = null): self

Markdown: a native textarea (screen readers, spelling, autofill and phones keep working), with a formatting toolbar (buttons and Ctrl+B, Ctrl+I, Ctrl+K) and Write and Preview tabs. The preview is sanitized (DOMPurify). It submits the Markdown text: render it on the server with a Markdown library that escapes HTML (league/commonmark with html_input "escape"). Without JavaScript it is a plain textarea.

markdownLabels ​

php
markdownLabels(array $labels): self

Texts of a markdown() field, for translation: toolbar (its name), bold, italic, heading, link, bulletList, numberedList, quote, code (the buttons), write and preview (the tabs) and empty (an empty preview).

code ​

php
static code(string $name, ?string $label = null): self

Code (CodeMirror 6, loaded only by forms that use it): line numbers, syntax colors, brackets, search (Ctrl+F) and Undo, in the theme's light or dark colors. Tab moves to the next field (no keyboard trap) unless tabIndents(); the keys are said under the editor. It submits the text of the textarea, which it keeps up to date; without JavaScript it is a plain textarea.

language ​

php
language(string $language): self

The language of a code() field, for its colors and indentation: text (default), javascript, typescript, jsx, php, html, css, json, sql, python, markdown or xml. Only its grammar is loaded.

tabIndents ​

php
tabIndents(bool $indents = true): self

Tab indents in a code() field, as in a code editor; Escape then Tab leaves it, which the text under the editor says.

codeLabels ​

php
codeLabels(array $labels): self

Texts of a code() field, for translation: keys (said under the editor) and tabKeys (instead, with tabIndents()).

signature ​

php
static signature(string $name, ?string $label = null): self

A signature: drawn with a mouse, a finger or a pen on a pad, or typed (the way for keyboards and screen readers, shown as handwriting on the pad). It submits a PNG image as a data URL (data:image/png;base64,...), which signatureImage() checks and decodes; without JavaScript, the pad is hidden and the typed name is submitted as text.

signatureLabels ​

php
signatureLabels(array $labels): self

Texts of a signature() field, for translation: draw (the instructions), type (the label of the name input), clear (the button), empty and signed (the pad's name) and missing (the message of a required field).

signatureImage ​

php
static signatureImage(mixed $value, int $maxBytes = self::SIGNATURE_MAX_BYTES): ?string

The PNG bytes of a submitted signature() value, or null when it is not a PNG data URL (the typed name, submitted as text without JavaScript, or anything else) or when it is larger than $maxBytes. Store the bytes as a file; never echo the value into a page.

rules ​

php
rules(UploadRules $rules): self

Accepted files for a file field (defaults to UploadRules::images()). Use the same rules in the UploadHandler.

imageEditor ​

php
imageEditor(array $ratios = ['free', '1:1', '4:3', '16:9'], ?int $maxSize = null): self

An image editor for a file field of one picture: once a picture is chosen, it can be cropped (free or in $ratios such as "1:1" or "16:9"), rotated and flipped, and the edited picture is the file sent, at most $maxSize pixels on its longest side. The crop area moves with the mouse, a finger, the arrow keys, or its position and size typed in numbers. Not with upload() or several files. Without JavaScript the file is sent as chosen.

  • $ratios: "free" and "width:height" shapes, the first one chosen first

imageEditorLabels ​

php
imageEditorLabels(array $labels): self

Texts of a file field's image editor, for translation (see IMAGE_EDITOR_LABELS).

upload ​

php
upload(string $url): self

Uploads each file asynchronously to this endpoint (FilePond server protocol: POST returns the id as text/plain, DELETE with the id as body reverts it). The form then submits the ids; claim them with UploadHandler::claim().

toolbar ​

php
toolbar(array|string $toolbar): self

Editor toolbar: "basic", "standard" (default), "full", or a Quill toolbar array.

searchable ​

php
searchable(bool $searchable = true): self

A select the user can type in to filter its choices (Tom Select). Works on multiple() selects too.

multiple ​

php
multiple(bool $multiple = true): self

Several choices: submits name[], and value() takes an array. Searchable selects show the choices as removable tags.

remote ​

php
remote(string $url, string $value = 'id', string $label = 'name', int $limit = 20): self

Loads the choices from an endpoint as the user types (GET $url?search=ada), and makes the select searchable. The endpoint answers with respond(), on the same field definition. The choices given to select() are the initial ones: include the selected value, so its label shows before any search.

  • $value: Field of the data source rows submitted as the value.
  • $label: Field shown, searched and sorted on.
  • $limit: Choices per search (1 to 100).

respond ​

php
respond(DataSourceInterface $source, array $query): DataResult

The endpoint of a remote() select: the first choices whose label contains the search term, sorted by label, as {"data": [{"value": …, "label": …}], "meta": {…}}. Only the value and label fields leave the data source.

inline ​

php
inline(bool $inline = true): self

Shows the choices of a radio or checkbox group on one line.

required ​

php
required(bool $required = true): self

minLength ​

php
minLength(int $length): self

maxLength ​

php
maxLength(int $length): self

min ​

php
min(string|int|float $min): self

max ​

php
max(string|int|float $max): self

step ​

php
step(string|int|float $step): self

Granularity of number, range, date and time fields, e.g. 0.5, or 900 (15 minutes, in seconds) for a time field.

pattern ​

php
pattern(string $pattern): self

HTML5 pattern (anchored implicitly, no delimiters), e.g. [A-Z]{2}[0-9]{4}.

equalTo ​

php
equalTo(string $fieldName): self

Requires the same value as another field of the form (password confirmation).

mask ​

php
mask(string $mask): self

Inputmask.js mask, e.g. 99/99/9999 or (999) 999-9999.

message ​

php
message(string $message): self

Custom client-side error message for every rule of this field.

placeholder ​

php
placeholder(string $placeholder): self

help ​

php
help(string $help): self

value ​

php
value(mixed $value): self

attribute ​

php
attribute(string $name, string|int|float|bool|null $value = true): self

columnSpan ​

php
columnSpan(string|int $span): self

How many columns of its form or section the field takes: a number, or "full".

getColumnSpan ​

php
getColumnSpan(): string|int|null

getName ​

php
getName(): string

withName ​

php
withName(string $name): self

A copy of the field under another name: a repeater's row, e.g. lines[0][product].

getLabel ​

php
getLabel(): string

getType ​

php
getType(): string

render ​

php
render(string $formId, ?string $error = null, mixed $value = null, bool $floating = false): string
  • $error: Server-side error message to display.
  • $value: Submitted value, takes precedence over the field default.
  • $floating: Bootstrap floating label (text-like inputs, selects and textareas only).

fieldId ​

php
static fieldId(string $formId, string $name): string

isFile ​

php
isFile(): bool

submitsArray ​

php
submitsArray(): bool

Whether the field submits an array: a date range, checkboxes, a multiple select or several files.

Grid ​

final class Caelrik\Ui\Components\Form\Grid

Lays out the fields and sections of a form or section in Bootstrap grid columns.

Constants ​

ConstantValue
COLUMNS[1, 2, 3, 4, 6]
BREAKPOINTS['sm', 'md', 'lg', 'xl', 'xxl']

Methods ​

assertColumns ​

php
static assertColumns(int $columns, string $breakpoint): void

assertSpan ​

php
static assertSpan(string|int $span): void

render ​

php
static render(array $items, int $columns, string $breakpoint, Closure $render): string

Repeater ​

final class Caelrik\Ui\Components\Form\Repeater

A group of fields the user repeats: order lines, addresses, contacts. Each row submits as name[key][field]; the user adds, removes and (with reorderable()) moves rows.

Row keys are kept: after a failed submit, old input and errors such as lines.2.qty find their row. They are not renumbered, so use array_values() if you need a list.

Constants ​

ConstantValue
PLACEHOLDER'__index__'

Methods ​

make ​

php
static make(string $name, ?string $label = null): self

schema ​

php
schema(Field ...$fields): self

The fields of one row. Their names are relative to the row: product submits as lines[0][product]. File, rich text and hidden fields are not supported in rows.

columns ​

php
columns(int $columns, string $breakpoint = 'md'): self

Lays a row's fields out in 1, 2, 3, 4 or 6 columns from a Bootstrap breakpoint up.

columnSpan ​

php
columnSpan(string|int $span): self

How many columns of its form or section the repeater takes: a number, or "full".

getColumnSpan ​

php
getColumnSpan(): string|int|null

min ​

php
min(int $min): self

The fewest rows: Remove is disabled at this count. Check it on the server too.

max ​

php
max(?int $max): self

The most rows: Add is disabled at this count. Check it on the server too.

defaultItems ​

php
defaultItems(int $count): self

How many empty rows a new form starts with (at least min()).

reorderable ​

php
reorderable(bool $reorderable = true): self

Move up and Move down buttons on each row. The rows submit in their order on screen.

help ​

php
help(?string $help): self

labels ​

php
labels(?string $add = null, ?string $remove = null, ?string $up = null, ?string $down = null, ?string $item = null): self

The button texts and each row's name; item takes the row's position (sprintf).

value ​

php
value(array $rows): self

The rows to show: a list of field => value arrays (e.g. the record's lines).

fill ​

php
fill(mixed $rows): void

The form's old input for this repeater, which wins over value().

getName ​

php
getName(): string

getFields ​

php
getFields(): array

The fields of every row, named for their row (lines[0][product]), in order.

render ​

php
render(string $formId, Closure $renderField, ?string $error): string

Section ​

final class Caelrik\Ui\Components\Form\Section

Groups the fields of a form: a section (a card with a heading, optionally collapsible) or a fieldset (a border and a legend, for controls that belong together, such as an address). Both can lay their fields out in columns and hold other sections.

Methods ​

make ​

php
static make(string $heading): self

A card with a heading (h2, h3 in a section).

fieldset ​

php
static fieldset(string $legend): self

A fieldset whose legend names its controls for screen readers.

add ​

php
add(Field|Section|Repeater ...$items): self

description ​

php
description(?string $description): self

columns ​

php
columns(int $columns, string $breakpoint = 'md'): self

Lays the items out in 1, 2, 3, 4 or 6 columns from a Bootstrap breakpoint up; one column below it.

columnSpan ​

php
columnSpan(string|int $span): self

How many columns of its form or parent section it takes: a number, or "full".

getColumnSpan ​

php
getColumnSpan(): string|int|null

collapsible ​

php
collapsible(bool $collapsed = false): self

A heading the user can click to show or hide the section (a native <details>). It opens by itself when a field inside it has an error.

id ​

php
id(string $id): self

The section's id; by default, the form's id and the heading.

getFields ​

php
getFields(): array

The fields of the section and its sections, in order.

render ​

php
render(string $formId, Closure $renderField, Closure $hasError, int $level = 2, ?string $stepLabel = null): string
php
                                           with its error and value
  • $level: the heading level: 2 in a form, 3 in a section
  • $stepLabel: a wizard step's "Step 1 of 3: ", for screen readers

getHeading ​

php
getHeading(): string

isFieldset ​

php
isFieldset(): bool

isCollapsible ​

php
isCollapsible(): bool

getItems ​

php
getItems(): array

hasErrors ​

php
hasErrors(Closure $hasError): bool

Whether a field or repeater of the section, or of its sections, has an error.

Wizard ​

final class Caelrik\Ui\Components\Form\Wizard

Renders a form's sections as the steps of a wizard (Form::wizard()): a step indicator, one step at a time, and Back, Next and submit buttons. form.js checks each step's fields before the next one; the whole form is submitted at the end.

Methods ​

__construct ​

php
__construct(string $next, string $previous, string $progress, string $stepOf, string $completed)

render ​

php
render(string $formId, array $items, Closure $renderField, Closure $hasError, ?string $submitLabel): string

Released under the MIT License.