update kirby to v5 and add refresh cache panel view button

This commit is contained in:
isUnknown 2025-09-10 14:28:38 +02:00
commit 9a86d41254
466 changed files with 19960 additions and 10497 deletions

View file

@ -3,13 +3,10 @@
namespace Kirby\Form;
use Closure;
use Exception;
use Kirby\Cms\App;
use Kirby\Cms\HasSiblings;
use Kirby\Exception\InvalidArgumentException;
use Kirby\Toolkit\A;
use Kirby\Toolkit\Component;
use Kirby\Toolkit\I18n;
use Kirby\Toolkit\V;
/**
* Form Field object that takes a Vue component style
@ -21,18 +18,25 @@ use Kirby\Toolkit\V;
* @link https://getkirby.com
* @copyright Bastian Allgeier
* @license https://opensource.org/licenses/MIT
*
* @use \Kirby\Cms\HasSiblings<\Kirby\Form\Fields>
*/
class Field extends Component
{
/**
* An array of all found errors
*/
protected array|null $errors = null;
use HasSiblings;
use Mixin\Api;
use Mixin\Model;
use Mixin\Translatable;
use Mixin\Validation;
use Mixin\When;
use Mixin\Value {
isEmptyValue as protected isEmptyValueFromMixin;
}
/**
* Parent collection with all fields of the current form
*/
protected Fields|null $formFields;
protected Fields $siblings;
/**
* Registry for all component mixins
@ -50,65 +54,31 @@ class Field extends Component
public function __construct(
string $type,
array $attrs = [],
Fields|null $formFields = null
Fields|null $siblings = null
) {
if (isset(static::$types[$type]) === false) {
throw new InvalidArgumentException([
'key' => 'field.type.missing',
'data' => ['name' => $attrs['name'] ?? '-', 'type' => $type]
]);
throw new InvalidArgumentException(
key: 'field.type.missing',
data: [
'name' => $attrs['name'] ?? '-',
'type' => $type
]
);
}
if (isset($attrs['model']) === false) {
throw new InvalidArgumentException('Field requires a model');
}
$this->formFields = $formFields;
// use the type as fallback for the name
$attrs['name'] ??= $type;
$attrs['type'] = $type;
// set the name to lowercase
$attrs['name'] = strtolower($attrs['name']);
$this->setModel($attrs['model'] ?? null);
parent::__construct($type, $attrs);
}
/**
* Returns field api call
*/
public function api(): mixed
{
if (
isset($this->options['api']) === true &&
$this->options['api'] instanceof Closure
) {
return $this->options['api']->call($this);
}
return null;
}
/**
* Returns field data
*/
public function data(bool $default = false): mixed
{
$save = $this->options['save'] ?? true;
if ($default === true && $this->isEmpty($this->value)) {
$value = $this->default();
} else {
$value = $this->value;
}
if ($save === false) {
return null;
}
if ($save instanceof Closure) {
return $save->call($this, $value);
}
return $value;
// set the siblings collection
$this->siblings = $siblings ?? new Fields([$this]);
}
/**
@ -191,7 +161,7 @@ class Field extends Component
return $when;
},
/**
* The width of the field in the field grid. Available widths: `1/1`, `1/2`, `1/3`, `1/4`, `2/3`, `3/4`
* The width of the field in the field grid, e.g. `1/1`, `1/2`, `1/3`, `1/4`, `2/3`, `3/4`
*/
'width' => function (string $width = '1/1') {
return $width;
@ -285,53 +255,84 @@ class Field extends Component
public static function factory(
string $type,
array $attrs = [],
Fields|null $formFields = null
Fields|null $siblings = null
): static|FieldClass {
$field = static::$types[$type] ?? null;
if (is_string($field) && class_exists($field) === true) {
$attrs['siblings'] = $formFields;
$attrs['siblings'] = $siblings;
return new $field($attrs);
}
return new static($type, $attrs, $formFields);
return new static($type, $attrs, $siblings);
}
/**
* Parent collection with all fields of the current form
* Sets a new value for the field
*/
public function formFields(): Fields|null
public function fill(mixed $value): static
{
return $this->formFields;
// remember the current state to restore it afterwards
$attrs = $this->attrs;
$methods = $this->methods;
$options = $this->options;
$type = $this->type;
// overwrite the attribute value
$this->value = $this->attrs['value'] = $value;
// reevaluate the value prop
$this->applyProp('value', $this->options['props']['value'] ?? $value);
// reevaluate the computed props
$this->applyComputed($this->options['computed'] ?? []);
// restore the original state
$this->attrs = $attrs;
$this->methods = $methods;
$this->options = $options;
$this->type = $type;
return $this;
}
/**
* Validates when run for the first time and returns any errors
* @deprecated 5.0.0 Use `::siblings() instead
*/
public function errors(): array
public function formFields(): Fields
{
if ($this->errors === null) {
$this->validate();
return $this->siblings;
}
/**
* Checks if the field has a value
*/
public function hasValue(): bool
{
return ($this->options['save'] ?? true) !== false;
}
/**
* Checks if the field is disabled
*/
public function isDisabled(): bool
{
return $this->disabled === true;
}
/**
* Checks if the given value is considered empty
*/
public function isEmptyValue(mixed $value = null): bool
{
if (
isset($this->options['isEmpty']) === true &&
$this->options['isEmpty'] instanceof Closure
) {
return $this->options['isEmpty']->call($this, $value);
}
return $this->errors;
}
/**
* Checks if the field is empty
*/
public function isEmpty(mixed ...$args): bool
{
$value = match (count($args)) {
0 => $this->value(),
default => $args[0]
};
if ($empty = $this->options['isEmpty'] ?? null) {
return $empty->call($this, $value);
}
return in_array($value, [null, '', []], true);
return $this->isEmptyValueFromMixin($value);
}
/**
@ -343,93 +344,34 @@ class Field extends Component
}
/**
* Checks if the field is invalid
* Returns field api routes
*/
public function isInvalid(): bool
public function routes(): array
{
return empty($this->errors()) === false;
}
/**
* Checks if the field is required
*/
public function isRequired(): bool
{
return $this->required ?? false;
}
/**
* Checks if the field is valid
*/
public function isValid(): bool
{
return empty($this->errors()) === true;
}
/**
* Returns the Kirby instance
*/
public function kirby(): App
{
return $this->model()->kirby();
}
/**
* Returns the parent model
*/
public function model(): mixed
{
return $this->model;
}
/**
* Checks if the field needs a value before being saved;
* this is the case if all of the following requirements are met:
* - The field is saveable
* - The field is required
* - The field is currently empty
* - The field is not currently inactive because of a `when` rule
*/
protected function needsValue(): bool
{
// check simple conditions first
if (
$this->save() === false ||
$this->isRequired() === false ||
$this->isEmpty() === false
isset($this->options['api']) === true &&
$this->options['api'] instanceof Closure
) {
return false;
return $this->options['api']->call($this);
}
// check the data of the relevant fields if there is a `when` option
if (
empty($this->when) === false &&
is_array($this->when) === true &&
$formFields = $this->formFields()
) {
foreach ($this->when as $field => $value) {
$field = $formFields->get($field);
$inputValue = $field?->value() ?? '';
// if the input data doesn't match the requested `when` value,
// that means that this field is not required and can be saved
// (*all* `when` conditions must be met for this field to be required)
if ($inputValue !== $value) {
return false;
}
}
}
// either there was no `when` condition or all conditions matched
return true;
return [];
}
/**
* Checks if the field is saveable
* Parent collection with all fields of the current form
*/
public function save(): bool
public function siblings(): Fields
{
return ($this->options['save'] ?? true) !== false;
return $this->siblings;
}
/**
* Returns all sibling fields for the HasSiblings trait
*/
protected function siblingsCollection(): Fields
{
return $this->siblings;
}
/**
@ -441,9 +383,8 @@ class Field extends Component
unset($array['model']);
$array['hidden'] = $this->isHidden();
$array['saveable'] = $this->save();
$array['signature'] = md5(json_encode($array));
$array['hidden'] = $this->isHidden();
$array['saveable'] = $this->hasValue();
ksort($array);
@ -454,57 +395,29 @@ class Field extends Component
}
/**
* Runs the validations defined for the field
* Returns the value of the field in a format to be stored by our storage classes
*/
protected function validate(): void
public function toStoredValue(): mixed
{
$validations = $this->options['validations'] ?? [];
$this->errors = [];
$value = $this->toFormValue();
$store = $this->options['save'] ?? true;
// validate required values
if ($this->needsValue() === true) {
$this->errors['required'] = I18n::translate('error.validation.required');
if ($store === false) {
return null;
}
foreach ($validations as $key => $validation) {
if (is_int($key) === true) {
// predefined validation
try {
Validations::$validation($this, $this->value());
} catch (Exception $e) {
$this->errors[$validation] = $e->getMessage();
}
continue;
}
if ($validation instanceof Closure) {
try {
$validation->call($this, $this->value());
} catch (Exception $e) {
$this->errors[$key] = $e->getMessage();
}
}
if ($store instanceof Closure) {
return $store->call($this, $value);
}
if (
empty($this->validate) === false &&
($this->isEmpty() === false || $this->isRequired() === true)
) {
$rules = A::wrap($this->validate);
$errors = V::errors($this->value(), $rules);
if (empty($errors) === false) {
$this->errors = array_merge($this->errors, $errors);
}
}
return $value;
}
/**
* Returns the value of the field if saveable
* otherwise it returns null
* Defines all validation rules
*/
public function value(): mixed
protected function validations(): array
{
return $this->save() ? $this->value : null;
return $this->options['validations'] ?? [];
}
}

View file

@ -8,6 +8,7 @@ use Kirby\Cms\Blocks as BlocksCollection;
use Kirby\Cms\Fieldset;
use Kirby\Cms\Fieldsets;
use Kirby\Cms\ModelWithContent;
use Kirby\Data\Json;
use Kirby\Exception\InvalidArgumentException;
use Kirby\Exception\NotFoundException;
use Kirby\Form\FieldClass;
@ -47,10 +48,11 @@ class BlocksField extends FieldClass
public function blocksToValues(
array $blocks,
string $to = 'values'
string $to = 'toFormValues'
): array {
$result = [];
$fields = [];
$forms = [];
foreach ($blocks as $block) {
try {
@ -58,12 +60,10 @@ class BlocksField extends FieldClass
// get and cache fields at the same time
$fields[$type] ??= $this->fields($block['type']);
$forms[$type] ??= $this->form($fields[$type]);
// overwrite the block content with form values
$block['content'] = $this->form(
$fields[$type],
$block['content']
)->$to();
$block['content'] = $forms[$type]->reset()->fill(input: $block['content'])->$to();
// create id if not exists
$block['id'] ??= Str::uuid();
@ -101,24 +101,29 @@ class BlocksField extends FieldClass
public function fieldsetGroups(): array|null
{
$groups = $this->fieldsets()->groups();
return empty($groups) === true ? null : $groups;
return $groups === [] ? null : $groups;
}
public function fill(mixed $value = null): void
/**
* @psalm-suppress MethodSignatureMismatch
* @todo Remove psalm suppress after https://github.com/vimeo/psalm/issues/8673 is fixed
*/
public function fill(mixed $value): static
{
$value = BlocksCollection::parse($value);
$blocks = BlocksCollection::factory($value)->toArray();
$this->value = $this->blocksToValues($blocks);
return $this;
}
public function form(array $fields, array $input = []): Form
public function form(array $fields): Form
{
return new Form([
'fields' => $fields,
'model' => $this->model,
'strict' => true,
'values' => $input,
]);
return new Form(
fields: $fields,
model: $this->model,
language: 'current'
);
}
public function isEmpty(): bool
@ -198,12 +203,13 @@ class BlocksField extends FieldClass
'action' => function (
string $fieldsetType
) use ($field): array {
$fields = $field->fields($fieldsetType);
$defaults = $field->form($fields, [])->data(true);
$content = $field->form($fields, $defaults)->values();
$fields = $field->fields($fieldsetType);
$form = $field->form($fields);
$form->fill(input: $form->defaults());
return Block::factory([
'content' => $content,
'content' => $form->toFormValues(),
'type' => $fieldsetType
])->toArray();
}
@ -221,10 +227,10 @@ class BlocksField extends FieldClass
$fieldApi = $this->clone([
'routes' => $field->api(),
'data' => array_merge(
$this->data(),
['field' => $field]
)
'data' => [
...$this->data(),
'field' => $field
]
]);
return $fieldApi->call(
@ -237,19 +243,6 @@ class BlocksField extends FieldClass
];
}
public function store(mixed $value): mixed
{
$blocks = $this->blocksToValues((array)$value, 'content');
// returns empty string to avoid storing empty array as string `[]`
// and to consistency work with `$field->isEmpty()`
if (empty($blocks) === true) {
return '';
}
return $this->valueToJson($blocks, $this->pretty());
}
protected function setDefault(mixed $default = null): void
{
// set id for blocks if not exists
@ -286,61 +279,80 @@ class BlocksField extends FieldClass
$this->pretty = $pretty;
}
public function toStoredValue(bool $default = false): mixed
{
$value = $this->toFormValue($default);
$blocks = $this->blocksToValues((array)$value, 'toStoredValues');
// returns empty string to avoid storing empty array as string `[]`
// and to consistency work with `$field->isEmpty()`
if ($blocks === []) {
return '';
}
return Json::encode($blocks, pretty: $this->pretty());
}
public function validations(): array
{
return [
'blocks' => function ($value) {
if ($this->min && count($value) < $this->min) {
throw new InvalidArgumentException([
'key' => 'blocks.min.' . ($this->min === 1 ? 'singular' : 'plural'),
'data' => [
'min' => $this->min
]
]);
throw new InvalidArgumentException(
key: match ($this->min) {
1 => 'blocks.min.singular',
default => 'blocks.min.plural'
},
data: ['min' => $this->min]
);
}
if ($this->max && count($value) > $this->max) {
throw new InvalidArgumentException([
'key' => 'blocks.max.' . ($this->max === 1 ? 'singular' : 'plural'),
'data' => [
'max' => $this->max
]
]);
throw new InvalidArgumentException(
key: match ($this->max) {
1 => 'blocks.max.singular',
default => 'blocks.max.plural'
},
data: ['max' => $this->max]
);
}
$fields = [];
$forms = [];
$index = 0;
foreach ($value as $block) {
$index++;
$type = $block['type'];
try {
$fieldset = $this->fieldset($type);
$blockFields = $fields[$type] ?? $fieldset->fields() ?? [];
} catch (Throwable) {
// skip invalid blocks
continue;
// create the form for the block
// and cache it for later use
if (isset($forms[$type]) === false) {
try {
$fieldset = $this->fieldset($type);
$fields = $fieldset->fields() ?? [];
$forms[$type] = $this->form($fields);
} catch (Throwable) {
// skip invalid blocks
continue;
}
}
// store the fields for the next round
$fields[$type] = $blockFields;
// overwrite the content with the serialized form
$form = $this->form($blockFields, $block['content']);
$form = $forms[$type]->reset()->fill($block['content']);
foreach ($form->fields() as $field) {
$errors = $field->errors();
// rough first validation
if (empty($errors) === false) {
throw new InvalidArgumentException([
'key' => 'blocks.validation',
'data' => [
if (count($errors) > 0) {
throw new InvalidArgumentException(
key:'blocks.validation',
data: [
'field' => $field->label(),
'fieldset' => $fieldset->name(),
'index' => $index
]
]);
);
}
}
}

View file

@ -0,0 +1,211 @@
<?php
namespace Kirby\Form\Field;
use Kirby\Data\Data;
use Kirby\Exception\InvalidArgumentException;
use Kirby\Form\FieldClass;
use Kirby\Form\Form;
use Kirby\Form\Mixin\EmptyState;
use Kirby\Form\Mixin\Max;
use Kirby\Form\Mixin\Min;
use Kirby\Toolkit\A;
use Kirby\Toolkit\Str;
/**
* Main class file of the entries field
*
* @package Kirby Field
* @author Ahmet Bora <ahmet@getkirby.com>
* @link https://getkirby.com
* @copyright Bastian Allgeier
* @license https://getkirby.com/license
* @since 5.0.0
*/
class EntriesField extends FieldClass
{
use EmptyState;
use Max;
use Min;
protected array $field;
protected Form $form;
protected bool $sortable = true;
public function __construct(array $params = [])
{
parent::__construct($params);
$this->setEmpty($params['empty'] ?? null);
$this->setField($params['field'] ?? null);
$this->setMax($params['max'] ?? null);
$this->setMin($params['min'] ?? null);
$this->setSortable($params['sortable'] ?? true);
}
public function field(): array
{
return $this->field;
}
public function fieldProps(): array
{
return $this->form()->fields()->first()->toArray();
}
/**
* @psalm-suppress MethodSignatureMismatch
* @todo Remove psalm suppress after https://github.com/vimeo/psalm/issues/8673 is fixed
*/
public function fill(mixed $value): static
{
$this->value = Data::decode($value ?? '', 'yaml');
return $this;
}
public function form(): Form
{
return $this->form ??= new Form(
fields: [$this->field()],
model: $this->model
);
}
public function props(): array
{
return [
...parent::props(),
'empty' => $this->empty(),
'field' => $this->fieldProps(),
'max' => $this->max(),
'min' => $this->min(),
'sortable' => $this->sortable(),
];
}
protected function setField(array|string|null $attrs = null): void
{
if (is_string($attrs) === true) {
$attrs = ['type' => $attrs];
}
$attrs ??= ['type' => 'text'];
if (in_array($attrs['type'], $this->supports()) === false) {
throw new InvalidArgumentException(
key: 'entries.supports',
data: ['type' => $attrs['type']]
);
}
// remove the unsupported props from the entry field
unset($attrs['counter'], $attrs['label']);
$this->field = $attrs;
}
protected function setSortable(bool|null $sortable = true): void
{
$this->sortable = $sortable;
}
public function sortable(): bool
{
return $this->sortable;
}
public function supports(): array
{
return [
'color',
'date',
'email',
'number',
'select',
'slug',
'tel',
'text',
'time',
'url'
];
}
public function toFormValue(): mixed
{
$form = $this->form();
$value = parent::toFormValue() ?? [];
return A::map(
$value,
fn ($value) => $form
->reset()
->fill(input: [$value])
->fields()
->first()
->toFormValue()
);
}
public function toStoredValue(): mixed
{
$form = $this->form();
$value = parent::toStoredValue();
return A::map(
$value,
fn ($value) => $form
->reset()
->submit(input: [$value])
->fields()
->first()
->toStoredValue()
);
}
public function validations(): array
{
return [
'entries' => function ($value) {
if ($this->min && count($value) < $this->min) {
throw new InvalidArgumentException(
key: match ($this->min) {
1 => 'entries.min.singular',
default => 'entries.min.plural'
},
data: ['min' => $this->min]
);
}
if ($this->max && count($value) > $this->max) {
throw new InvalidArgumentException(
key: match ($this->max) {
1 => 'entries.max.singular',
default => 'entries.max.plural'
},
data: ['max' => $this->max]
);
}
$form = $this->form();
foreach ($value as $index => $val) {
$form->reset()->submit(input: [$val]);
foreach ($form->fields() as $field) {
$errors = $field->errors();
if ($errors !== []) {
throw new InvalidArgumentException(
key: 'entries.validation',
data: [
'field' => $this->label() ?? Str::ucfirst($this->name()),
'index' => $index + 1
]
);
}
}
}
}
];
}
}

View file

@ -7,6 +7,8 @@ use Kirby\Cms\Blueprint;
use Kirby\Cms\Fieldset;
use Kirby\Cms\Layout;
use Kirby\Cms\Layouts;
use Kirby\Data\Data;
use Kirby\Data\Json;
use Kirby\Exception\InvalidArgumentException;
use Kirby\Form\Form;
use Kirby\Toolkit\Str;
@ -28,14 +30,19 @@ class LayoutField extends BlocksField
parent::__construct($params);
}
public function fill(mixed $value = null): void
/**
* @psalm-suppress MethodSignatureMismatch
* @todo Remove psalm suppress after https://github.com/vimeo/psalm/issues/8673 is fixed
*/
public function fill(mixed $value): static
{
$value = $this->valueFromJson($value);
$attrs = $this->attrsForm();
$value = Data::decode($value, type: 'json', fail: false);
$layouts = Layouts::factory($value, ['parent' => $this->model])->toArray();
foreach ($layouts as $layoutIndex => $layout) {
if ($this->settings !== null) {
$layouts[$layoutIndex]['attrs'] = $this->attrsForm($layout['attrs'])->values();
$layouts[$layoutIndex]['attrs'] = $attrs->reset()->fill($layout['attrs'])->toFormValues();
}
foreach ($layout['columns'] as $columnIndex => $column) {
@ -44,18 +51,16 @@ class LayoutField extends BlocksField
}
$this->value = $layouts;
return $this;
}
public function attrsForm(array $input = []): Form
public function attrsForm(): Form
{
$settings = $this->settings();
return new Form([
'fields' => $settings?->fields() ?? [],
'model' => $this->model,
'strict' => true,
'values' => $input,
]);
return new Form(
fields: $this->settings()?->fields() ?? [],
model: $this->model
);
}
public function layouts(): array|null
@ -96,7 +101,7 @@ class LayoutField extends BlocksField
// remove the row if layout not available for the pasted layout field
$columns = array_column($layout['columns'], 'width');
if (in_array($columns, $this->layouts()) === false) {
if (in_array($columns, $this->layouts(), true) === false) {
unset($layouts[$layoutIndex]);
continue;
}
@ -122,13 +127,12 @@ class LayoutField extends BlocksField
public function props(): array
{
$settings = $this->settings();
return array_merge(parent::props(), [
return [
...parent::props(),
'layouts' => $this->layouts(),
'selector' => $this->selector(),
'settings' => $settings?->toArray()
]);
'settings' => $this->settings()?->toArray()
];
}
public function routes(): array
@ -142,13 +146,14 @@ class LayoutField extends BlocksField
'action' => function () use ($field): array {
$request = App::instance()->request();
$input = $request->get('attrs') ?? [];
$defaults = $field->attrsForm($input)->data(true);
$attrs = $field->attrsForm($defaults)->values();
$columns = $request->get('columns') ?? ['1/1'];
$columns = $request->get('columns') ?? ['1/1'];
$form = $field->attrsForm();
$form->fill(input: $form->defaults());
$form->submit(input: $request->get('attrs') ?? []);
return Layout::factory([
'attrs' => $attrs,
'attrs' => $form->toFormValues(),
'columns' => array_map(fn ($width) => [
'blocks' => [],
'id' => Str::uuid(),
@ -182,10 +187,10 @@ class LayoutField extends BlocksField
$fieldApi = $this->clone([
'routes' => $field->api(),
'data' => array_merge(
$this->data(),
['field' => $field]
)
'data' => [
...$this->data(),
'field' => $field
]
]);
return $fieldApi->call(
@ -267,19 +272,21 @@ class LayoutField extends BlocksField
return $this->settings;
}
public function store(mixed $value): mixed
public function toStoredValue(bool $default = false): mixed
{
$attrs = $this->attrsForm();
$value = $this->toFormValue($default);
$value = Layouts::factory($value, ['parent' => $this->model])->toArray();
// returns empty string to avoid storing empty array as string `[]`
// and to consistency work with `$field->isEmpty()`
if (empty($value) === true) {
if ($value === []) {
return '';
}
foreach ($value as $layoutIndex => $layout) {
if ($this->settings !== null) {
$value[$layoutIndex]['attrs'] = $this->attrsForm($layout['attrs'])->content();
$value[$layoutIndex]['attrs'] = $attrs->reset()->fill($layout['attrs'])->toStoredValues();
}
foreach ($layout['columns'] as $columnIndex => $column) {
@ -287,32 +294,31 @@ class LayoutField extends BlocksField
}
}
return $this->valueToJson($value, $this->pretty());
return Json::encode($value, pretty: $this->pretty());
}
public function validations(): array
{
return [
'layout' => function ($value) {
$fields = [];
$attrsForm = $this->attrsForm();
$blockForms = [];
$layoutIndex = 0;
foreach ($value as $layout) {
$layoutIndex++;
// validate settings form
$form = $this->attrsForm($layout['attrs'] ?? []);
$form = $attrsForm->reset()->fill($layout['attrs'] ?? []);
foreach ($form->fields() as $field) {
$errors = $field->errors();
if (empty($errors) === false) {
throw new InvalidArgumentException([
'key' => 'layout.validation.settings',
'data' => [
'index' => $layoutIndex
]
]);
if (count($errors) > 0) {
throw new InvalidArgumentException(
key:'layout.validation.settings',
data: ['index' => $layoutIndex]
);
}
}
@ -324,34 +330,34 @@ class LayoutField extends BlocksField
$blockIndex++;
$blockType = $block['type'];
try {
$fieldset = $this->fieldset($blockType);
$blockFields = $fields[$blockType] ?? $this->fields($blockType) ?? [];
} catch (Throwable) {
// skip invalid blocks
continue;
if (isset($blockForms[$blockType]) === false) {
try {
$fieldset = $this->fieldset($blockType);
$fields = $this->fields($blockType) ?? [];
$blockForms[$blockType] = $this->form($fields);
} catch (Throwable) {
// skip invalid blocks
continue;
}
}
// store the fields for the next round
$fields[$blockType] = $blockFields;
// overwrite the content with the serialized form
$form = $this->form($blockFields, $block['content']);
$form = $blockForms[$blockType]->reset()->fill($block['content']);
foreach ($form->fields() as $field) {
$errors = $field->errors();
// rough first validation
if (empty($errors) === false) {
throw new InvalidArgumentException([
'key' => 'layout.validation.block',
'data' => [
if (count($errors) > 0) {
throw new InvalidArgumentException(
key: 'layout.validation.block',
data: [
'blockIndex' => $blockIndex,
'field' => $field->label(),
'fieldset' => $fieldset->name(),
'layoutIndex' => $layoutIndex
]
]);
);
}
}
}

View file

@ -2,15 +2,9 @@
namespace Kirby\Form;
use Closure;
use Exception;
use Kirby\Cms\App;
use Kirby\Cms\HasSiblings;
use Kirby\Cms\ModelWithContent;
use Kirby\Data\Data;
use Kirby\Toolkit\I18n;
use Kirby\Toolkit\Str;
use Throwable;
/**
* Abstract field class to be used instead
@ -22,27 +16,29 @@ use Throwable;
* @link https://getkirby.com
* @copyright Bastian Allgeier
* @license https://getkirby.com/license
*
* @use \Kirby\Cms\HasSiblings<\Kirby\Form\Fields>
*/
abstract class FieldClass
{
use HasSiblings;
use Mixin\Api;
use Mixin\Model;
use Mixin\Translatable;
use Mixin\Validation;
use Mixin\Value;
use Mixin\When;
protected string|null $after;
protected bool $autofocus;
protected string|null $before;
protected mixed $default;
protected bool $disabled;
protected string|null $help;
protected string|null $icon;
protected string|null $label;
protected ModelWithContent $model;
protected string|null $name;
protected string|null $placeholder;
protected bool $required;
protected Fields $siblings;
protected bool $translate;
protected mixed $value = null;
protected array|null $when;
protected string|null $width;
public function __construct(
@ -56,7 +52,7 @@ abstract class FieldClass
$this->setHelp($params['help'] ?? null);
$this->setIcon($params['icon'] ?? null);
$this->setLabel($params['label'] ?? null);
$this->setModel($params['model'] ?? App::instance()->site());
$this->setModel($params['model'] ?? null);
$this->setName($params['name'] ?? null);
$this->setPlaceholder($params['placeholder'] ?? null);
$this->setRequired($params['required'] ?? false);
@ -84,11 +80,6 @@ abstract class FieldClass
return $this->stringTemplate($this->after);
}
public function api(): array
{
return $this->routes();
}
public function autofocus(): bool
{
return $this->autofocus;
@ -99,32 +90,6 @@ abstract class FieldClass
return $this->stringTemplate($this->before);
}
/**
* @deprecated 3.5.0
* @todo remove when the general field class setup has been refactored
*
* Returns the field data
* in a format to be stored
* in Kirby's content fields
*/
public function data(bool $default = false): mixed
{
return $this->store($this->value($default));
}
/**
* Returns the default value for the field,
* which will be used when a page/file/user is created
*/
public function default(): mixed
{
if (is_string($this->default) === false) {
return $this->default;
}
return $this->stringTemplate($this->default);
}
/**
* Returns optional dialog routes for the field
*/
@ -149,23 +114,6 @@ abstract class FieldClass
return [];
}
/**
* Runs all validations and returns an array of
* error messages
*/
public function errors(): array
{
return $this->validate();
}
/**
* Setter for the value
*/
public function fill(mixed $value = null): void
{
$this->value = $value;
}
/**
* Optional help text below the field
*/
@ -203,55 +151,11 @@ abstract class FieldClass
return $this->disabled;
}
public function isEmpty(): bool
{
return $this->isEmptyValue($this->value());
}
public function isEmptyValue(mixed $value = null): bool
{
return in_array($value, [null, '', []], true);
}
public function isHidden(): bool
{
return false;
}
/**
* Checks if the field is invalid
*/
public function isInvalid(): bool
{
return $this->isValid() === false;
}
public function isRequired(): bool
{
return $this->required;
}
public function isSaveable(): bool
{
return true;
}
/**
* Checks if the field is valid
*/
public function isValid(): bool
{
return empty($this->errors()) === true;
}
/**
* Returns the Kirby instance
*/
public function kirby(): App
{
return $this->model->kirby();
}
/**
* The field label can be set as string or associative array with translations
*/
@ -262,14 +166,6 @@ abstract class FieldClass
);
}
/**
* Returns the parent model
*/
public function model(): ModelWithContent
{
return $this->model;
}
/**
* Returns the field name
*/
@ -278,48 +174,6 @@ abstract class FieldClass
return $this->name ?? $this->type();
}
/**
* Checks if the field needs a value before being saved;
* this is the case if all of the following requirements are met:
* - The field is saveable
* - The field is required
* - The field is currently empty
* - The field is not currently inactive because of a `when` rule
*/
protected function needsValue(): bool
{
// check simple conditions first
if (
$this->isSaveable() === false ||
$this->isRequired() === false ||
$this->isEmpty() === false
) {
return false;
}
// check the data of the relevant fields if there is a `when` option
if (
empty($this->when) === false &&
is_array($this->when) === true &&
$formFields = $this->siblings()
) {
foreach ($this->when as $field => $value) {
$field = $formFields->get($field);
$inputValue = $field?->value() ?? '';
// if the input data doesn't match the requested `when` value,
// that means that this field is not required and can be saved
// (*all* `when` conditions must be met for this field to be required)
if ($inputValue !== $value) {
return false;
}
}
}
// either there was no `when` condition or all conditions matched
return true;
}
/**
* Returns all original params for the field
*/
@ -355,7 +209,7 @@ abstract class FieldClass
'name' => $this->name(),
'placeholder' => $this->placeholder(),
'required' => $this->isRequired(),
'saveable' => $this->isSaveable(),
'saveable' => $this->hasValue(),
'translate' => $this->translate(),
'type' => $this->type(),
'when' => $this->when(),
@ -363,31 +217,6 @@ abstract class FieldClass
];
}
/**
* If `true`, the field has to be filled in correctly to be saved.
*/
public function required(): bool
{
return $this->required;
}
/**
* Routes for the field API
*/
public function routes(): array
{
return [];
}
/**
* @deprecated 3.5.0
* @todo remove when the general field class setup has been refactored
*/
public function save(): bool
{
return $this->isSaveable();
}
protected function setAfter(array|string|null $after = null): void
{
$this->after = $this->i18n($after);
@ -403,11 +232,6 @@ abstract class FieldClass
$this->before = $this->i18n($before);
}
protected function setDefault(mixed $default = null): void
{
$this->default = $default;
}
protected function setDisabled(bool $disabled = false): void
{
$this->disabled = $disabled;
@ -428,14 +252,9 @@ abstract class FieldClass
$this->label = $this->i18n($label);
}
protected function setModel(ModelWithContent $model): void
{
$this->model = $model;
}
protected function setName(string|null $name = null): void
{
$this->name = $name;
$this->name = strtolower($name ?? $this->type());
}
protected function setPlaceholder(array|string|null $placeholder = null): void
@ -443,29 +262,11 @@ abstract class FieldClass
$this->placeholder = $this->i18n($placeholder);
}
protected function setRequired(bool $required = false): void
{
$this->required = $required;
}
protected function setSiblings(Fields|null $siblings = null): void
{
$this->siblings = $siblings ?? new Fields([$this]);
}
protected function setTranslate(bool $translate = true): void
{
$this->translate = $translate;
}
/**
* Setter for the when condition
*/
protected function setWhen(array|null $when = null): void
{
$this->when = $when;
}
/**
* Setter for the field width
*/
@ -475,7 +276,7 @@ abstract class FieldClass
}
/**
* Returns all sibling fields
* Returns all sibling fields for the HasSiblings trait
*/
protected function siblingsCollection(): Fields
{
@ -494,30 +295,12 @@ abstract class FieldClass
return null;
}
/**
* Converts the given value to a value
* that can be stored in the text file
*/
public function store(mixed $value): mixed
{
return $value;
}
/**
* Should the field be translatable?
*/
public function translate(): bool
{
return $this->translate;
}
/**
* Converts the field to a plain array
*/
public function toArray(): array
{
$props = $this->props();
$props['signature'] = md5(json_encode($props));
ksort($props);
@ -532,109 +315,6 @@ abstract class FieldClass
return lcfirst(basename(str_replace(['\\', 'Field'], ['/', ''], static::class)));
}
/**
* Runs the validations defined for the field
*/
protected function validate(): array
{
$validations = $this->validations();
$value = $this->value();
$errors = [];
// validate required values
if ($this->needsValue() === true) {
$errors['required'] = I18n::translate('error.validation.required');
}
foreach ($validations as $key => $validation) {
if (is_int($key) === true) {
// predefined validation
try {
Validations::$validation($this, $value);
} catch (Exception $e) {
$errors[$validation] = $e->getMessage();
}
continue;
}
if ($validation instanceof Closure) {
try {
$validation->call($this, $value);
} catch (Exception $e) {
$errors[$key] = $e->getMessage();
}
}
}
return $errors;
}
/**
* Defines all validation rules
* @codeCoverageIgnore
*/
protected function validations(): array
{
return [];
}
/**
* Returns the value of the field if saveable
* otherwise it returns null
*/
public function value(bool $default = false): mixed
{
if ($this->isSaveable() === false) {
return null;
}
if ($default === true && $this->isEmpty() === true) {
return $this->default();
}
return $this->value;
}
protected function valueFromJson(mixed $value): array
{
try {
return Data::decode($value, 'json');
} catch (Throwable) {
return [];
}
}
protected function valueFromYaml(mixed $value): array
{
return Data::decode($value, 'yaml');
}
protected function valueToJson(
array|null $value = null,
bool $pretty = false
): string {
$constants = JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE;
if ($pretty === true) {
$constants |= JSON_PRETTY_PRINT;
}
return json_encode($value, $constants);
}
protected function valueToYaml(array|null $value = null): string
{
return Data::encode($value, 'yaml');
}
/**
* Conditions when the field will be shown
*/
public function when(): array|null
{
return $this->when;
}
/**
* Returns the width of the field in
* the Panel grid

View file

@ -3,7 +3,14 @@
namespace Kirby\Form;
use Closure;
use Kirby\Cms\App;
use Kirby\Cms\Language;
use Kirby\Cms\ModelWithContent;
use Kirby\Exception\InvalidArgumentException;
use Kirby\Exception\NotFoundException;
use Kirby\Toolkit\A;
use Kirby\Toolkit\Collection;
use Kirby\Toolkit\Str;
/**
* A collection of Field objects
@ -13,27 +20,309 @@ use Kirby\Toolkit\Collection;
* @link https://getkirby.com
* @copyright Bastian Allgeier
* @license https://opensource.org/licenses/MIT
*
* @extends \Kirby\Toolkit\Collection<\Kirby\Form\Field|\Kirby\Form\FieldClass>
*/
class Fields extends Collection
{
protected Language $language;
protected ModelWithContent $model;
protected array $passthrough = [];
public function __construct(
array $fields = [],
ModelWithContent|null $model = null,
Language|string|null $language = null
) {
$this->model = $model ?? App::instance()->site();
$this->language = Language::ensure($language ?? 'current');
foreach ($fields as $name => $field) {
$this->__set($name, $field);
}
}
/**
* Internal setter for each object in the Collection.
* This takes care of validation and of setting
* the collection prop on each object correctly.
*
* @param object|array $field
* @param \Kirby\Form\Field|\Kirby\Form\FieldClass|array $field
*/
public function __set(string $name, $field): void
{
if (is_array($field) === true) {
// use the array key as name if the name is not set
$field['name'] ??= $name;
$field['model'] ??= $this->model;
$field['name'] ??= $name;
$field = Field::factory($field['type'], $field, $this);
}
parent::__set($field->name(), $field);
}
/**
* Returns an array with the default value of each field
*
* @since 5.0.0
*/
public function defaults(): array
{
return $this->toArray(fn ($field) => $field->default());
}
/**
* An array of all found in all fields errors
*/
public function errors(): array
{
$errors = [];
foreach ($this->data as $name => $field) {
$fieldErrors = $field->errors();
if ($fieldErrors !== []) {
$errors[$name] = [
'label' => $field->label(),
'message' => $fieldErrors
];
}
}
return $errors;
}
/**
* Get the field object by name
* and handle nested fields correctly
*
* @since 5.0.0
* @throws \Kirby\Exception\NotFoundException
*/
public function field(string $name): Field|FieldClass
{
if ($field = $this->find($name)) {
return $field;
}
throw new NotFoundException(
message: 'The field could not be found'
);
}
/**
* Sets the value for each field with a matching key in the input array
*
* @since 5.0.0
*/
public function fill(
array $input,
bool $passthrough = true
): static {
if ($passthrough === true) {
$this->passthrough($input);
}
foreach ($input as $name => $value) {
if (!$field = $this->get($name)) {
continue;
}
// don't change the value of non-value field
if ($field->hasValue() === false) {
continue;
}
// resolve closure values
if ($value instanceof Closure) {
$value = $value($field->toFormValue());
}
$field->fill($value);
}
return $this;
}
/**
* Find a field by key/name
*/
public function findByKey(string $key): Field|FieldClass|null
{
if (str_contains($key, '+')) {
return $this->findByKeyRecursive($key);
}
return parent::findByKey($key);
}
/**
* Find fields in nested forms recursively
*/
public function findByKeyRecursive(string $key): Field|FieldClass|null
{
$fields = $this;
$names = Str::split($key, '+');
$index = 0;
$count = count($names);
$field = null;
foreach ($names as $name) {
$index++;
// search for the field by name
$field = $fields->get($name);
// if the field cannot be found,
// there's no point in going further
if ($field === null) {
return null;
}
// there are more parts in the key
if ($index < $count) {
$form = $field->form();
// the search can only continue for
// fields with valid nested forms
if ($form instanceof Form === false) {
return null;
}
$fields = $form->fields();
}
}
return $field;
}
/**
* Creates a new Fields instance for the given model and language
*
* @since 5.0.0
*/
public static function for(
ModelWithContent $model,
Language|string|null $language = null
): static {
return new static(
fields: $model->blueprint()->fields(),
model: $model,
language: $language,
);
}
/**
* Returns the language of the fields
*
* @since 5.0.0
*/
public function language(): Language
{
return $this->language;
}
/**
* Adds values to the passthrough array
* which will be added to the form data
* if the field does not exist
*
* @since 5.0.0
*/
public function passthrough(array|null $values = null): static|array
{
// use passthrough method as getter if the value is null
if ($values === null) {
return $this->passthrough;
}
foreach ($values as $key => $value) {
$key = strtolower($key);
// check if the field exists and don't passthrough
// values for existing fields
if ($this->get($key) !== null) {
continue;
}
// resolve closure values
if ($value instanceof Closure) {
$value = $value($this->passthrough[$key] ?? null);
}
$this->passthrough[$key] = $value;
}
return $this;
}
/**
* Resets the value of each field
*
* @since 5.0.0
*/
public function reset(): static
{
// reset the passthrough values
$this->passthrough = [];
// reset the values of each field
foreach ($this->data as $field) {
$field->fill(null);
}
return $this;
}
/**
* Sets the value for each field with a matching key in the input array
* but only if the field is not disabled
*
* @since 5.0.0
* @param bool $passthrough If true, values for undefined fields will be submitted
* @param bool $force If true, values for fields that cannot be submitted (e.g. disabled or untranslatable fields) will be submitted
*/
public function submit(
array $input,
bool $passthrough = true,
bool $force = false
): static {
$language = $this->language();
if ($passthrough === true) {
$this->passthrough($input);
}
foreach ($input as $name => $value) {
if (!$field = $this->get($name)) {
continue;
}
// don't submit fields without a value
if ($force === true && $field->hasValue() === false) {
continue;
}
// don't submit fields that are not submittable
if ($force === false && $field->isSubmittable($language) === false) {
continue;
}
// resolve closure values
if ($value instanceof Closure) {
$value = $value($field->toFormValue());
}
// submit the value to the field
// the field class might override this method
// to handle submitted values differently
$field->submit($value);
}
// reset the errors cache
return $this;
}
/**
* Converts the fields collection to an
* array and also does that for every
@ -41,12 +330,103 @@ class Fields extends Collection
*/
public function toArray(Closure|null $map = null): array
{
$array = [];
return A::map($this->data, $map ?? fn ($field) => $field->toArray());
}
foreach ($this as $field) {
$array[$field->name()] = $field->toArray();
/**
* Returns an array with the form value of each field
* (e.g. used as data for Panel Vue components)
*
* @since 5.0.0
*/
public function toFormValues(): array
{
return $this->toValues(
fn ($field) => $field->toFormValue(),
fn ($field) => $field->hasValue()
);
}
/**
* Returns an array with the props of each field
* for the frontend
*
* @since 5.0.0
*/
public function toProps(): array
{
$fields = $this->data;
$props = [];
$language = $this->language();
$permissions = $this->model->permissions()->can('update');
foreach ($fields as $name => $field) {
$props[$name] = $field->toArray();
// the field should be disabled in the form if the user
// has no update permissions for the model or if the field
// is not translatable into the current language
if ($permissions === false || $field->isTranslatable($language) === false) {
$props[$name]['disabled'] = true;
}
// the value should not be included in the props
// we pass on the values to the frontend via the model
// view props to make them globally available for the view.
unset($props[$name]['value']);
}
return $array;
return $props;
}
/**
* Returns an array with the stored value of each field
* (e.g. used for saving to content storage)
*
* @since 5.0.0
*/
public function toStoredValues(): array
{
return $this->toValues(
fn ($field) => $field->toStoredValue(),
fn ($field) => $field->isStorable($this->language())
);
}
/**
* Returns an array with the values of each field
* and adds passthrough values if they don't exist
* @unstable
*/
protected function toValues(Closure $method, Closure $filter): array
{
$values = $this->filter($filter)->toArray($method);
foreach ($this->passthrough as $key => $value) {
if (isset($values[$key]) === false) {
$values[$key] = $value;
}
}
return $values;
}
/**
* Checks for errors in all fields and throws an
* exception if there are any
*
* @since 5.0.0
* @throws \Kirby\Exception\InvalidArgumentException
*/
public function validate(): void
{
$errors = $this->errors();
if ($errors !== []) {
throw new InvalidArgumentException(
fallback: 'Invalid form with errors',
details: $errors
);
}
}
}

View file

@ -2,15 +2,11 @@
namespace Kirby\Form;
use Closure;
use Kirby\Cms\App;
use Kirby\Cms\File;
use Kirby\Cms\Language;
use Kirby\Cms\ModelWithContent;
use Kirby\Data\Data;
use Kirby\Exception\NotFoundException;
use Kirby\Toolkit\A;
use Kirby\Toolkit\Str;
use Throwable;
/**
* The main form class, that is being
@ -26,88 +22,37 @@ use Throwable;
*/
class Form
{
/**
* An array of all found errors
*/
protected array|null $errors = null;
/**
* Fields in the form
*/
protected Fields|null $fields;
/**
* All values of form
*/
protected array $values = [];
protected Fields $fields;
/**
* Form constructor
*/
public function __construct(array $props)
{
$fields = $props['fields'] ?? [];
$values = $props['values'] ?? [];
$input = $props['input'] ?? [];
$strict = $props['strict'] ?? false;
$inject = $props;
public function __construct(
array $props = [],
array $fields = [],
ModelWithContent|null $model = null,
Language|string|null $language = null
) {
if ($props !== []) {
$this->legacyConstruct(...$props);
return;
}
// prepare field properties for multilang setups
$fields = static::prepareFieldsForLanguage(
$fields,
$props['language'] ?? null
$this->fields = new Fields(
fields: $fields,
model: $model,
language: $language
);
// lowercase all value names
$values = array_change_key_case($values);
$input = array_change_key_case($input);
unset($inject['fields'], $inject['values'], $inject['input']);
$this->fields = new Fields();
$this->values = [];
foreach ($fields as $name => $props) {
// inject stuff from the form constructor (model, etc.)
$props = array_merge($inject, $props);
// inject the name
$props['name'] = $name = strtolower($name);
// check if the field is disabled and
// overwrite the field value if not set
$props['value'] = match ($props['disabled'] ?? false) {
true => $values[$name] ?? null,
default => $input[$name] ?? $values[$name] ?? null
};
try {
$field = Field::factory($props['type'], $props, $this->fields);
} catch (Throwable $e) {
$field = static::exceptionField($e, $props);
}
if ($field->save() !== false) {
$this->values[$name] = $field->value();
}
$this->fields->append($name, $field);
}
if ($strict !== true) {
// use all given values, no matter
// if there's a field or not.
$input = array_merge($values, $input);
foreach ($input as $key => $value) {
$this->values[$key] ??= $value;
}
}
}
/**
* Returns the data required to write to the content file
* Doesn't include default and null values
*
* @deprecated 5.0.0 Use `::toStoredValues()` instead
*/
public function content(): array
{
@ -117,71 +62,54 @@ class Form
/**
* Returns data for all fields in the form
*
* @param false $defaults
* @deprecated 5.0.0 Use `::toStoredValues()` instead
*/
public function data($defaults = false, bool $includeNulls = true): array
{
$data = $this->values;
$data = [];
$language = $this->fields->language();
foreach ($this->fields as $field) {
if ($field->save() === false || $field->unset() === true) {
if ($field->isStorable($language) === false) {
if ($includeNulls === true) {
$data[$field->name()] = null;
} else {
unset($data[$field->name()]);
}
} else {
$data[$field->name()] = $field->data($defaults);
continue;
}
if ($defaults === true && $field->isEmpty() === true) {
$field->fill($field->default());
}
$data[$field->name()] = $field->toStoredValue();
}
foreach ($this->fields->passthrough() as $key => $value) {
if (isset($data[$key]) === false) {
$data[$key] = $value;
}
}
return $data;
}
/**
* Returns an array with the default value of each field
*
* @since 5.0.0
*/
public function defaults(): array
{
return $this->fields->defaults();
}
/**
* An array of all found errors
*/
public function errors(): array
{
if ($this->errors !== null) {
return $this->errors;
}
$this->errors = [];
foreach ($this->fields as $field) {
if (empty($field->errors()) === false) {
$this->errors[$field->name()] = [
'label' => $field->label(),
'message' => $field->errors()
];
}
}
return $this->errors;
}
/**
* Shows the error with the field
*/
public static function exceptionField(
Throwable $exception,
array $props = []
): Field {
$message = $exception->getMessage();
if (App::instance()->option('debug') === true) {
$message .= ' in file: ' . $exception->getFile();
$message .= ' line: ' . $exception->getLine();
}
$props = array_merge($props, [
'label' => 'Error in "' . $props['name'] . '" field.',
'theme' => 'negative',
'text' => strip_tags($message),
]);
return Field::factory('info', $props);
return $this->fields->errors();
}
/**
@ -192,81 +120,59 @@ class Form
*/
public function field(string $name): Field|FieldClass
{
$form = $this;
$fieldNames = Str::split($name, '+');
$index = 0;
$count = count($fieldNames);
$field = null;
foreach ($fieldNames as $fieldName) {
$index++;
if ($field = $form->fields()->get($fieldName)) {
if ($count !== $index) {
$form = $field->form();
}
continue;
}
throw new NotFoundException('The field "' . $fieldName . '" could not be found');
}
// it can get this error only if $name is an empty string as $name = ''
if ($field === null) {
throw new NotFoundException('No field could be loaded');
}
return $field;
return $this->fields->field($name);
}
/**
* Returns form fields
*/
public function fields(): Fields|null
public function fields(): Fields
{
return $this->fields;
}
/**
* Sets the value for each field with a matching key in the input array
*
* @since 5.0.0
*/
public function fill(
array $input,
bool $passthrough = true
): static {
$this->fields->fill(
input: $input,
passthrough: $passthrough
);
return $this;
}
/**
* Creates a new Form instance for the given model with the fields
* from the blueprint and the values from the content
*/
public static function for(
ModelWithContent $model,
array $props = []
array $props = [],
Language|string|null $language = null,
): static {
// get the original model data
$original = $model->content($props['language'] ?? null)->toArray();
$values = $props['values'] ?? [];
// convert closures to values
foreach ($values as $key => $value) {
if ($value instanceof Closure) {
$values[$key] = $value($original[$key] ?? null);
}
if ($props !== []) {
return static::legacyFor(
$model,
...$props
);
}
// set a few defaults
$props['values'] = array_merge($original, $values);
$props['fields'] ??= [];
$props['model'] = $model;
$form = new static(
fields: $model->blueprint()->fields(),
model: $model,
language: $language
);
// search for the blueprint
if (
method_exists($model, 'blueprint') === true &&
$blueprint = $model->blueprint()
) {
$props['fields'] = $blueprint->fields();
}
// fill the form with the latest content of the model
$form->fill(input: $model->content($form->language())->toArray());
$ignoreDisabled = $props['ignoreDisabled'] ?? false;
// REFACTOR: this could be more elegant
if ($ignoreDisabled === true) {
$props['fields'] = array_map(function ($field) {
$field['disabled'] = false;
return $field;
}, $props['fields']);
}
return new static($props);
return $form;
}
/**
@ -282,43 +188,116 @@ class Form
*/
public function isValid(): bool
{
return empty($this->errors()) === true;
return $this->fields->errors() === [];
}
/**
* Disables fields in secondary languages when
* they are configured to be untranslatable
* Returns the language of the form
*
* @since 5.0.0
*/
protected static function prepareFieldsForLanguage(
array $fields,
string|null $language = null
): array {
$kirby = App::instance(null, true);
public function language(): Language
{
return $this->fields->language();
}
// only modify the fields if we have a valid Kirby multilang instance
if ($kirby?->multilang() !== true) {
return $fields;
/**
* Legacy constructor to support the old props array
*
* @deprecated 5.0.0 Use the new constructor with named parameters instead
*/
protected function legacyConstruct(
array $fields = [],
ModelWithContent|null $model = null,
Language|string|null $language = null,
array $values = [],
array $input = [],
bool $strict = false
): void {
$this->__construct(
fields: $fields,
model: $model,
language: $language
);
$this->fill(
input: $values,
passthrough: $strict === false
);
$this->submit(
input: $input,
passthrough: $strict === false
);
}
/**
* Legacy for method to support the old props array
*
* @deprecated 5.0.0 Use `::for()` with named parameters instead
*/
protected static function legacyFor(
ModelWithContent $model,
Language|string|null $language = null,
bool $strict = false,
array|null $input = [],
array|null $values = [],
bool $ignoreDisabled = false
): static {
$form = static::for(
model: $model,
language: $language,
);
$form->fill(
input: $values ?? [],
passthrough: $strict === false
);
$form->submit(
input: $input ?? [],
passthrough: $strict === false
);
return $form;
}
/**
* Adds values to the passthrough array
* which will be added to the form data
* if the field does not exist
*
* @since 5.0.0
*/
public function passthrough(
array|null $values = null
): static|array {
if ($values === null) {
return $this->fields->passthrough();
}
$language ??= $kirby->language()->code();
$this->fields->passthrough(
values: $values
);
if ($language !== $kirby->defaultLanguage()->code()) {
foreach ($fields as $fieldName => $fieldProps) {
// switch untranslatable fields to readonly
if (($fieldProps['translate'] ?? true) === false) {
$fields[$fieldName]['unset'] = true;
$fields[$fieldName]['disabled'] = true;
}
}
}
return $this;
}
return $fields;
/**
* Resets the value of each field
*
* @since 5.0.0
*/
public function reset(): static
{
$this->fields->reset();
return $this;
}
/**
* Converts the data of fields to strings
*
* @param false $defaults
* @deprecated 5.0.0 Use `::toStoredValues()` instead
*/
public function strings($defaults = false): array
{
@ -331,25 +310,91 @@ class Form
);
}
/**
* Sets the value for each field with a matching key in the input array
* but only if the field is not disabled
*
* @since 5.0.0
* @param bool $passthrough If true, values for undefined fields will be submitted
* @param bool $force If true, values for fields that cannot be submitted (e.g. disabled or untranslatable fields) will be submitted
*/
public function submit(
array $input,
bool $passthrough = true,
bool $force = false
): static {
$this->fields->submit(
input: $input,
passthrough: $passthrough,
force: $force
);
return $this;
}
/**
* Converts the form to a plain array
*/
public function toArray(): array
{
$array = [
'errors' => $this->errors(),
'fields' => $this->fields->toArray(fn ($item) => $item->toArray()),
'errors' => $this->fields->errors(),
'fields' => $this->fields->toArray(),
'invalid' => $this->isInvalid()
];
return $array;
}
/**
* Returns an array with the form value of each field
* (e.g. used as data for Panel Vue components)
*
* @since 5.0.0
*/
public function toFormValues(): array
{
return $this->fields->toFormValues();
}
/**
* Returns an array with the props of each field
* for the frontend
*
* @since 5.0.0
*/
public function toProps(): array
{
return $this->fields->toProps();
}
/**
* Returns an array with the stored value of each field
* (e.g. used for saving to content storage)
*
* @since 5.0.0
*/
public function toStoredValues(): array
{
return $this->fields->toStoredValues();
}
/**
* Validates the form and throws an exception if there are any errors
*
* @throws \Kirby\Exception\InvalidArgumentException
*/
public function validate(): void
{
$this->fields->validate();
}
/**
* Returns form values
*
* @deprecated 5.0.0 Use `::toFormValues()` instead
*/
public function values(): array
{
return $this->values;
return $this->fields->toFormValues();
}
}

View file

@ -0,0 +1,19 @@
<?php
namespace Kirby\Form\Mixin;
trait Api
{
public function api(): array
{
return $this->routes();
}
/**
* Routes for the field API
*/
public function routes(): array
{
return [];
}
}

View file

@ -8,6 +8,11 @@ trait Min
public function min(): int|null
{
// set min to at least 1, if required
if ($this->required === true) {
return $this->min ?? 1;
}
return $this->min;
}
@ -15,4 +20,14 @@ trait Min
{
$this->min = $min;
}
public function isRequired(): bool
{
// set required to true if min is set
if ($this->min) {
return true;
}
return $this->required;
}
}

View file

@ -0,0 +1,35 @@
<?php
namespace Kirby\Form\Mixin;
use Kirby\Cms\App;
use Kirby\Cms\ModelWithContent;
trait Model
{
protected ModelWithContent $model;
/**
* Returns the Kirby instance
*/
public function kirby(): App
{
return $this->model->kirby();
}
/**
* Returns the parent model
*/
public function model(): ModelWithContent
{
return $this->model;
}
/**
* Sets the parent model
*/
protected function setModel(ModelWithContent|null $model = null): void
{
$this->model = $model ?? App::instance()->site();
}
}

View file

@ -0,0 +1,47 @@
<?php
namespace Kirby\Form\Mixin;
use Kirby\Cms\Language;
/**
* @package Kirby Form
* @author Bastian Allgeier <bastian@getkirby.com>
* @link https://getkirby.com
* @copyright Bastian Allgeier
* @license https://opensource.org/licenses/MIT
*/
trait Translatable
{
protected bool $translate = true;
/**
* Should the field be translatable into the given language?
*
* @since 5.0.0
*/
public function isTranslatable(Language $language): bool
{
if ($this->translate() === false && $language->isDefault() === false) {
return false;
}
return true;
}
/**
* Set the translatable status
*/
protected function setTranslate(bool $translate = true): void
{
$this->translate = $translate;
}
/**
* Should the field be translatable?
*/
public function translate(): bool
{
return $this->translate;
}
}

View file

@ -0,0 +1,117 @@
<?php
namespace Kirby\Form\Mixin;
use Closure;
use Exception;
use Kirby\Form\Validations;
use Kirby\Toolkit\A;
use Kirby\Toolkit\I18n;
use Kirby\Toolkit\V;
/**
* @package Kirby Form
* @author Bastian Allgeier <bastian@getkirby.com>
* @link https://getkirby.com
* @copyright Bastian Allgeier
* @license https://opensource.org/licenses/MIT
*/
trait Validation
{
protected bool $required;
/**
* Runs all validations and returns an array of
* error messages
*/
public function errors(): array
{
$validations = $this->validations();
$value = $this->value();
$errors = [];
// validate required values
if ($this->needsValue() === true) {
$errors['required'] = I18n::translate('error.validation.required');
}
foreach ($validations as $key => $validation) {
if (is_int($key) === true) {
// predefined validation
try {
Validations::$validation($this, $value);
} catch (Exception $e) {
$errors[$validation] = $e->getMessage();
}
continue;
}
if ($validation instanceof Closure) {
try {
$validation->call($this, $value);
} catch (Exception $e) {
$errors[$key] = $e->getMessage();
}
}
}
if (
empty($this->validate) === false &&
($this->isEmpty() === false || $this->isRequired() === true)
) {
$rules = A::wrap($this->validate);
$errors = [
...$errors,
...V::errors($value, $rules)
];
}
return $errors;
}
/**
* Checks if the field is required
*/
public function isRequired(): bool
{
return $this->required;
}
/**
* Checks if the field is invalid
*/
public function isInvalid(): bool
{
return $this->errors() !== [];
}
/**
* Checks if the field is valid
*/
public function isValid(): bool
{
return $this->errors() === [];
}
/**
* Getter for the required property
*/
public function required(): bool
{
return $this->required;
}
protected function setRequired(bool $required = false): void
{
$this->required = $required;
}
/**
* Defines all validation rules
*/
protected function validations(): array
{
return [];
}
}

View file

@ -0,0 +1,212 @@
<?php
namespace Kirby\Form\Mixin;
use Kirby\Cms\Language;
/**
* @package Kirby Form
* @author Bastian Allgeier <bastian@getkirby.com>
* @link https://getkirby.com
* @copyright Bastian Allgeier
* @license https://opensource.org/licenses/MIT
*/
trait Value
{
protected mixed $default = null;
protected mixed $value = null;
/**
* @deprecated 5.0.0 Use `::toStoredValue()` instead to receive
* the value in the format that will be needed for content files.
*
* If you need to get the value with the default as fallback, you should use
* the fill method first `$field->fill($field->default())->toStoredValue()`
*/
public function data(bool $default = false): mixed
{
if ($default === true && $this->isEmpty() === true) {
$this->fill($this->default());
}
return $this->toStoredValue();
}
/**
* Returns the default value of the field
*/
public function default(): mixed
{
if (is_string($this->default) === false) {
return $this->default;
}
return $this->model->toString($this->default);
}
/**
* Sets a new value for the field
*/
public function fill(mixed $value): static
{
$this->value = $value;
return $this;
}
/**
* Checks if the field has a value
*/
public function hasValue(): bool
{
return true;
}
/**
* Checks if the field is empty
*/
public function isEmpty(): bool
{
return $this->isEmptyValue($this->toFormValue());
}
/**
* Checks if the given value is considered empty
*/
public function isEmptyValue(mixed $value = null): bool
{
return in_array($value, [null, '', []], true);
}
/**
* Checks if the field can be stored in the given language.
*/
public function isStorable(Language $language): bool
{
// the field cannot be stored at all if it has no value
if ($this->hasValue() === false) {
return false;
}
// the field cannot be translated into the given language
if ($this->isTranslatable($language) === false) {
return false;
}
// We don't need to check if the field is disabled.
// A disabled field can still have a value and that value
// should still be stored. But that value must not be changed
// on submit. That's why we check for the disabled state
// in the isSubmittable method.
return true;
}
/**
* A field might have a value, but can still not be submitted
* because it is disabled, not translatable into the given
* language or not active due to a `when` rule.
*/
public function isSubmittable(Language $language): bool
{
if ($this->hasValue() === false) {
return false;
}
if ($this->isTranslatable($language) === false) {
return false;
}
return true;
}
/**
* Checks if the field needs a value before being saved;
* this is the case if all of the following requirements are met:
* - The field has a value
* - The field is required
* - The field is currently empty
* - The field is not currently inactive because of a `when` rule
*/
protected function needsValue(): bool
{
if (
$this->hasValue() === false ||
$this->isRequired() === false ||
$this->isEmpty() === false ||
$this->isActive() === false
) {
return false;
}
return true;
}
/**
* Checks if the field is saveable
* @deprecated 5.0.0 Use `::hasValue()` instead
*/
public function save(): bool
{
return $this->hasValue();
}
protected function setDefault(mixed $default = null): void
{
$this->default = $default;
}
/**
* Submits a new value for the field.
* Fields can overwrite this method to provide custom
* submit logic. This is useful if the field component
* sends data that needs to be processed before being
* stored.
*
* @since 5.0.0
*/
public function submit(mixed $value): static
{
return $this->fill($value);
}
/**
* Returns the value of the field in a format to be used in forms
* (e.g. used as data for Panel Vue components)
*/
public function toFormValue(): mixed
{
if ($this->hasValue() === false) {
return null;
}
return $this->value;
}
/**
* Returns the value of the field in a format
* to be stored by our storage classes
*/
public function toStoredValue(): mixed
{
return $this->toFormValue();
}
/**
* Returns the value of the field if it has a value
* otherwise it returns null
*
* @see `self::toFormValue()`
* @todo might get deprecated or reused later. Use `self::toFormValue()` instead.
*
* If you need the form value with the default as fallback, you should use
* the fill method first `$field->fill($field->default())->toFormValue()`
*/
public function value(bool $default = false): mixed
{
if ($default === true && $this->isEmpty() === true) {
$this->fill($this->default());
}
return $this->toFormValue();
}
}

View file

@ -0,0 +1,58 @@
<?php
namespace Kirby\Form\Mixin;
/**
* @package Kirby Form
* @author Bastian Allgeier <bastian@getkirby.com>
* @link https://getkirby.com
* @copyright Bastian Allgeier
* @license https://opensource.org/licenses/MIT
*/
trait When
{
protected array|null $when = null;
/**
* Checks if the field is currently active
* or hidden because of a `when` condition
*/
public function isActive(): bool
{
if ($this->when === null || $this->when === []) {
return true;
}
$siblings = $this->siblings();
foreach ($this->when as $field => $value) {
$field = $siblings->get($field);
$input = $field?->value() ?? '';
// if the input data doesn't match the requested `when` value,
// that means that this field is not required and can be saved
// (*all* `when` conditions must be met for this field to be required)
if ($input !== $value) {
return false;
}
}
return true;
}
/**
* Setter for the `when` condition
*/
protected function setWhen(array|null $when = null): void
{
$this->when = $when;
}
/**
* Returns the `when` condition of the field
*/
public function when(): array|null
{
return $this->when;
}
}

View file

@ -24,11 +24,11 @@ class Validations
*/
public static function boolean($field, $value): bool
{
if ($field->isEmpty($value) === false) {
if ($field->isEmptyValue($value) === false) {
if (is_bool($value) === false) {
throw new InvalidArgumentException([
'key' => 'validation.boolean'
]);
throw new InvalidArgumentException(
key: 'validation.boolean'
);
}
}
@ -42,10 +42,10 @@ class Validations
*/
public static function date(Field|FieldClass $field, mixed $value): bool
{
if ($field->isEmpty($value) === false) {
if ($field->isEmptyValue($value) === false) {
if (V::date($value) !== true) {
throw new InvalidArgumentException(
V::message('date', $value)
message: V::message('date', $value)
);
}
}
@ -60,10 +60,10 @@ class Validations
*/
public static function email(Field|FieldClass $field, mixed $value): bool
{
if ($field->isEmpty($value) === false) {
if ($field->isEmptyValue($value) === false) {
if (V::email($value) === false) {
throw new InvalidArgumentException(
V::message('email', $value)
message: V::message('email', $value)
);
}
}
@ -79,12 +79,12 @@ class Validations
public static function max(Field|FieldClass $field, mixed $value): bool
{
if (
$field->isEmpty($value) === false &&
$field->isEmptyValue($value) === false &&
$field->max() !== null
) {
if (V::max($value, $field->max()) === false) {
throw new InvalidArgumentException(
V::message('max', $value, $field->max())
message: V::message('max', $value, $field->max())
);
}
}
@ -100,12 +100,12 @@ class Validations
public static function maxlength(Field|FieldClass $field, mixed $value): bool
{
if (
$field->isEmpty($value) === false &&
$field->isEmptyValue($value) === false &&
$field->maxlength() !== null
) {
if (V::maxLength($value, $field->maxlength()) === false) {
throw new InvalidArgumentException(
V::message('maxlength', $value, $field->maxlength())
message: V::message('maxlength', $value, $field->maxlength())
);
}
}
@ -121,12 +121,12 @@ class Validations
public static function min(Field|FieldClass $field, mixed $value): bool
{
if (
$field->isEmpty($value) === false &&
$field->isEmptyValue($value) === false &&
$field->min() !== null
) {
if (V::min($value, $field->min()) === false) {
throw new InvalidArgumentException(
V::message('min', $value, $field->min())
message: V::message('min', $value, $field->min())
);
}
}
@ -142,12 +142,12 @@ class Validations
public static function minlength(Field|FieldClass $field, mixed $value): bool
{
if (
$field->isEmpty($value) === false &&
$field->isEmptyValue($value) === false &&
$field->minlength() !== null
) {
if (V::minLength($value, $field->minlength()) === false) {
throw new InvalidArgumentException(
V::message('minlength', $value, $field->minlength())
message: V::message('minlength', $value, $field->minlength())
);
}
}
@ -162,7 +162,7 @@ class Validations
*/
public static function pattern(Field|FieldClass $field, mixed $value): bool
{
if ($field->isEmpty($value) === false) {
if ($field->isEmptyValue($value) === false) {
if ($pattern = $field->pattern()) {
// ensure that that pattern needs to match the whole
// input value from start to end, not just a partial match
@ -171,7 +171,7 @@ class Validations
if (V::match($value, '/' . $pattern . '/i') === false) {
throw new InvalidArgumentException(
V::message('match')
message: V::message('match')
);
}
}
@ -188,13 +188,13 @@ class Validations
public static function required(Field|FieldClass $field, mixed $value): bool
{
if (
$field->hasValue() === true &&
$field->isRequired() === true &&
$field->save() === true &&
$field->isEmpty($value) === true
$field->isEmptyValue($value) === true
) {
throw new InvalidArgumentException([
'key' => 'validation.required'
]);
throw new InvalidArgumentException(
key: 'validation.required'
);
}
return true;
@ -207,13 +207,13 @@ class Validations
*/
public static function option(Field|FieldClass $field, mixed $value): bool
{
if ($field->isEmpty($value) === false) {
if ($field->isEmptyValue($value) === false) {
$values = array_column($field->options(), 'value');
if (in_array($value, $values, true) !== true) {
throw new InvalidArgumentException([
'key' => 'validation.option'
]);
throw new InvalidArgumentException(
key: 'validation.option'
);
}
}
@ -227,13 +227,13 @@ class Validations
*/
public static function options(Field|FieldClass $field, mixed $value): bool
{
if ($field->isEmpty($value) === false) {
if ($field->isEmptyValue($value) === false) {
$values = array_column($field->options(), 'value');
foreach ($value as $val) {
if (in_array($val, $values, true) === false) {
throw new InvalidArgumentException([
'key' => 'validation.option'
]);
throw new InvalidArgumentException(
key: 'validation.option'
);
}
}
}
@ -248,10 +248,10 @@ class Validations
*/
public static function time(Field|FieldClass $field, mixed $value): bool
{
if ($field->isEmpty($value) === false) {
if ($field->isEmptyValue($value) === false) {
if (V::time($value) !== true) {
throw new InvalidArgumentException(
V::message('time', $value)
message: V::message('time', $value)
);
}
}
@ -266,10 +266,10 @@ class Validations
*/
public static function url(Field|FieldClass $field, mixed $value): bool
{
if ($field->isEmpty($value) === false) {
if ($field->isEmptyValue($value) === false) {
if (V::url($value) === false) {
throw new InvalidArgumentException(
V::message('url', $value)
message: V::message('url', $value)
);
}
}