Validation in custom fields

I would like to implement proper validation for the Kirby Builder. The field contains a variable number of dynamic subfields, which can be valid or invalid. If one of the subfields is invalid, the entire kirby Builder field should be invalid aswell.

  • How can I detect if a field of a child component is invalid?
  • How can I set my custom field to be invalid, so that the page can not be saved?

You can add custom validations like this:

Kirby::plugin('timoetting/kirbybuilder', [
    'fields' => [
        'builder' => [
            // …
            'validations' => [
                'name-of-the-validation' => function ($values) {
                    throw new Excpetion('Oops! Something went wrong');
                }
            ]
        ]
    ]
]);

For the validation you can probably utilize the Kirby\Form\Form class. It basically works like this:

use Kirby\Form\Form;

$form = new Form([
    'fields' => [
        'title' => [
            'label' => 'Title',
            'type' => 'text',
            'required' => true,
        ],
        'subtitle' => [
          'label' => 'Subitle',
          'type' => 'text',
        ]
    ],
    'values' => [
        'subtitle' => 'Lorem ipsum dolor sit amet',
    ]
]);

if ($form->errors()) {
    throw new Excpetion('Oops! Something went wrong');
}