Custom form validation on panel field

I’m trying to validate a number field for having a specific min value that I’m reading from another field, therefore I can’t set it in the blueprint.
I tried it with a page.update:after hook, but when I change the page there, the changes only are visible are reloading in the frontend:

'page.update:after' => function (Kirby\Cms\Page $newPage, Kirby\Cms\Page $oldPage) {
   // validation failed, set variable back to what it was before
   $newPage->update([
       'myVar' =>  $myVal
   ]);
}

I also tried adding a validator in a plugin, but there I only have access to the value of the field and not to the other pages I’d need to read too.

How could I achieve such a validation or how can I return an error from the hook?

To throw an error, you would have to use a page.update:before hook.

But maybe a custom validator is the better option.

Is the field you want to get the value from in the same page? Or what is the relation?

the field is on the same page, yes! How could I do this with the validator? I only got $value there which was the current value, as shown in Validators | Kirby CMS

how could I throw an error from page.update:before?

This hook would throw an error if the current value is lower than the value given in the minValue field (change field names as appropriate).

   'hooks' => [
        'page.update:before' => function ($page) {
            $min = $page->minValue()->toInt(); // or use toFloat if you field uses floats
            if ($page->myVar()->toInt() < $min) {
                throw new Exception('Min value must be ' . $min);
            }
        }
    ]

A custom validator indeed would not work because you don’t have access to the current page in this context.

1 Like

works like a charm, thank you very much!