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
| Constant | Value |
|---|---|
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_BYTES | 512000 |
PAIR_PLACEHOLDER | '__pair__' |
Methods
input
static input(string $type, string $name, ?string $label = null): selftext
static text(string $name, ?string $label = null): selfemail
static email(string $name, ?string $label = null): selfpassword
static password(string $name, ?string $label = null): selfnumber
static number(string $name, ?string $label = null): selftel
static tel(string $name, ?string $label = null): selfdate
static date(string $name, ?string $label = null): selfA date (YYYY-MM-DD), with the browser's date picker.
time
static time(string $name, ?string $label = null): selfA time (HH:MM, or HH:MM:SS with a step under 60), with the browser's time picker.
datetime
static datetime(string $name, ?string $label = null): selfA 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
static dateRange(string $name, ?string $label = null, string $type = 'date'): selfA 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
labels(string $start, string $end): selfLabels of the two inputs of a dateRange() field (default "From" and "To").
hidden
static hidden(string $name, string|int|float $value): selftextarea
static textarea(string $name, ?string $label = null): selfselect
static select(string $name, array $choices, ?string $label = null): selftags
static tags(string $name, array $suggestions = [], ?string $label = null): selfFree-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
minTags(int $min): selfThe fewest tags of a tags() field. It makes the field required: required() alone is minTags(1).
maxTags
maxTags(int $max): selfThe most tags of a tags() field: the user cannot add more.
addText
addText(string $text): selfThe text offering a new tag in the list, %s being what the user typed (default "Add %s").
rating
static rating(string $name, ?string $label = null): selfA 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
stars(int $count): selfHow many stars a rating() field has (3 to 10, default 5).
ratingLabels
ratingLabels(?string $star = null, ?string $clear = null): selfTexts 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
static otp(string $name, ?string $label = null): selfA 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
codeLength(int $length): selfHow many characters a one-time code has (4 to 10, default 6).
alphanumeric
alphanumeric(bool $alphanumeric = true): selfA one-time code of letters and digits, e.g. K7M2QX, instead of digits only.
keyValue
static keyValue(string $name, ?string $label = null): selfA 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
keySuggestions(array $keys): selfKeys the key inputs suggest as the user types (a datalist), e.g. common HTTP headers. Other keys are accepted.
keyValueLabels
keyValueLabels(?string $key = null, ?string $value = null, ?string $add = null, ?string $remove = null, ?string $missing = null, ?string $duplicate = null): selfThe 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
static keyValues(mixed $rows): arrayThe 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
static checkbox(string $name, ?string $label = null): selfswitch
static switch(string $name, ?string $label = null): selfOn/off switch: a checkbox shown as a toggle, announced as a switch. Submits "1" when on.
radio
static radio(string $name, array $choices, ?string $label = null): selfRadio buttons in a fieldset, the label as its legend. required() requires a choice.
checkboxes
static checkboxes(string $name, array $choices, ?string $label = null): selfCheckboxes 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
static range(string $name, ?string $label = null): selfSlider (min 0, max 100 and step 1 unless set). The current value is shown next to the label.
color
static color(string $name, ?string $label = null): selfColor picker. Submits a lowercase hex color such as #0d6efd.
file
static file(string $name, ?string $label = null): selfFile 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
static editor(string $name, ?string $label = null): selfRich text editor (Quill). Submits HTML: always sanitize it on the server (see EditorHtml::sanitize()).
markdown
static markdown(string $name, ?string $label = null): selfMarkdown: 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
markdownLabels(array $labels): selfTexts 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
static code(string $name, ?string $label = null): selfCode (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
language(string $language): selfThe 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
tabIndents(bool $indents = true): selfTab indents in a code() field, as in a code editor; Escape then Tab leaves it, which the text under the editor says.
codeLabels
codeLabels(array $labels): selfTexts of a code() field, for translation: keys (said under the editor) and tabKeys (instead, with tabIndents()).
signature
static signature(string $name, ?string $label = null): selfA 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
signatureLabels(array $labels): selfTexts 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
static signatureImage(mixed $value, int $maxBytes = self::SIGNATURE_MAX_BYTES): ?stringThe 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
rules(UploadRules $rules): selfAccepted files for a file field (defaults to UploadRules::images()). Use the same rules in the UploadHandler.
imageEditor
imageEditor(array $ratios = ['free', '1:1', '4:3', '16:9'], ?int $maxSize = null): selfAn 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
imageEditorLabels(array $labels): selfTexts of a file field's image editor, for translation (see IMAGE_EDITOR_LABELS).
upload
upload(string $url): selfUploads 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
toolbar(array|string $toolbar): selfEditor toolbar: "basic", "standard" (default), "full", or a Quill toolbar array.
searchable
searchable(bool $searchable = true): selfA select the user can type in to filter its choices (Tom Select). Works on multiple() selects too.
multiple
multiple(bool $multiple = true): selfSeveral choices: submits name[], and value() takes an array. Searchable selects show the choices as removable tags.
remote
remote(string $url, string $value = 'id', string $label = 'name', int $limit = 20): selfLoads 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
respond(DataSourceInterface $source, array $query): DataResultThe 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
inline(bool $inline = true): selfShows the choices of a radio or checkbox group on one line.
required
required(bool $required = true): selfminLength
minLength(int $length): selfmaxLength
maxLength(int $length): selfmin
min(string|int|float $min): selfmax
max(string|int|float $max): selfstep
step(string|int|float $step): selfGranularity of number, range, date and time fields, e.g. 0.5, or 900 (15 minutes, in seconds) for a time field.
pattern
pattern(string $pattern): selfHTML5 pattern (anchored implicitly, no delimiters), e.g. [A-Z]{2}[0-9]{4}.
equalTo
equalTo(string $fieldName): selfRequires the same value as another field of the form (password confirmation).
mask
mask(string $mask): selfInputmask.js mask, e.g. 99/99/9999 or (999) 999-9999.
message
message(string $message): selfCustom client-side error message for every rule of this field.
placeholder
placeholder(string $placeholder): selfhelp
help(string $help): selfvalue
value(mixed $value): selfattribute
attribute(string $name, string|int|float|bool|null $value = true): selfcolumnSpan
columnSpan(string|int $span): selfHow many columns of its form or section the field takes: a number, or "full".
getColumnSpan
getColumnSpan(): string|int|nullgetName
getName(): stringwithName
withName(string $name): selfA copy of the field under another name: a repeater's row, e.g. lines[0][product].
getLabel
getLabel(): stringgetType
getType(): stringrender
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
static fieldId(string $formId, string $name): stringisFile
isFile(): boolsubmitsArray
submitsArray(): boolWhether 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
| Constant | Value |
|---|---|
COLUMNS | [1, 2, 3, 4, 6] |
BREAKPOINTS | ['sm', 'md', 'lg', 'xl', 'xxl'] |
Methods
assertColumns
static assertColumns(int $columns, string $breakpoint): voidassertSpan
static assertSpan(string|int $span): voidrender
static render(array $items, int $columns, string $breakpoint, Closure $render): stringRepeater
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
| Constant | Value |
|---|---|
PLACEHOLDER | '__index__' |
Methods
make
static make(string $name, ?string $label = null): selfschema
schema(Field ...$fields): selfThe 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
columns(int $columns, string $breakpoint = 'md'): selfLays a row's fields out in 1, 2, 3, 4 or 6 columns from a Bootstrap breakpoint up.
columnSpan
columnSpan(string|int $span): selfHow many columns of its form or section the repeater takes: a number, or "full".
getColumnSpan
getColumnSpan(): string|int|nullmin
min(int $min): selfThe fewest rows: Remove is disabled at this count. Check it on the server too.
max
max(?int $max): selfThe most rows: Add is disabled at this count. Check it on the server too.
defaultItems
defaultItems(int $count): selfHow many empty rows a new form starts with (at least min()).
reorderable
reorderable(bool $reorderable = true): selfMove up and Move down buttons on each row. The rows submit in their order on screen.
help
help(?string $help): selflabels
labels(?string $add = null, ?string $remove = null, ?string $up = null, ?string $down = null, ?string $item = null): selfThe button texts and each row's name; item takes the row's position (sprintf).
value
value(array $rows): selfThe rows to show: a list of field => value arrays (e.g. the record's lines).
fill
fill(mixed $rows): voidThe form's old input for this repeater, which wins over value().
getName
getName(): stringgetFields
getFields(): arrayThe fields of every row, named for their row (lines[0][product]), in order.
render
render(string $formId, Closure $renderField, ?string $error): stringSection
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
static make(string $heading): selfA card with a heading (h2, h3 in a section).
fieldset
static fieldset(string $legend): selfA fieldset whose legend names its controls for screen readers.
add
add(Field|Section|Repeater ...$items): selfdescription
description(?string $description): selfcolumns
columns(int $columns, string $breakpoint = 'md'): selfLays the items out in 1, 2, 3, 4 or 6 columns from a Bootstrap breakpoint up; one column below it.
columnSpan
columnSpan(string|int $span): selfHow many columns of its form or parent section it takes: a number, or "full".
getColumnSpan
getColumnSpan(): string|int|nullcollapsible
collapsible(bool $collapsed = false): selfA 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
id(string $id): selfThe section's id; by default, the form's id and the heading.
getFields
getFields(): arrayThe fields of the section and its sections, in order.
render
render(string $formId, Closure $renderField, Closure $hasError, int $level = 2, ?string $stepLabel = null): string 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
getHeading(): stringisFieldset
isFieldset(): boolisCollapsible
isCollapsible(): boolgetItems
getItems(): arrayhasErrors
hasErrors(Closure $hasError): boolWhether 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
__construct(string $next, string $previous, string $progress, string $stepOf, string $completed)render
render(string $formId, array $items, Closure $renderField, Closure $hasError, ?string $submitLabel): string