Custom field preprocess values before save

I’m trying to figure out how I can create a custom field that preprocesses values (e.g. check if the value represents a valid page and if not, create one) before saving them back to the file.

I tend to believe I need some kind of controller for that, but I cannot find in the docs how I would achieve something like this. Can someone point me in the right direction/help me out?


Maybe my preview field can serve as a starting point. The user selects a page and based on that value, a preview page is called. You might as well use the same sort of logic to test if the page exists and create a new one.

Hi @texnixe, I had a quick glance at your plugin. Correct me if I’m wrong, but I think the logic for “preprocessing” is situated in the javascript, right? (e.g. “on change of select” -> “do something”)

I can’t do that, since I don’t want to start creating pages on each field blur/change, but only when they save the page. The logic that would actually do that is going to be PHP-based anyway so I wouldn’t want to make it extra complicated and have this logic in both back- and front-end. (An alert that pops up on error would be enough, I think.)

I would like to use some kind of “pre-save-hook” for a field. Does this exist?
If not, can a field have a controller that does this? And how? A link to a plugin or core field that just does this would be golden.

You could use the result() method in your custom field. The method returns / prepares the value that is actually saved to the file when you hit save in the panel. Perhaps that helps.

thx @lukaskleinschmidt. I’ll have a look into this.

Is there some reference which method does what for fields?
Tbh I find it hard to figure out what does what, which methods are required, what is execution flow, …
Is there a reference or docs available that cover this?

I can only recommend to look in the source files of kirby to get a grip on what really is going on.

@bvdputte, I understand. @lukaskleinschmidt has already pointed you to the result method. The validate method might be an alternative, not sure.

Unfortunately, there is no documentation. But the base field is a good starting point to get an idea what does what in fields.

Hmmm, I just came around to test this and in my experience this gets always called on inputfield “onchange”-event via AJAX. That is not what I was hoping for. As the editor could still be in a “conceptually draft mode”, I really don’t want to have Kirby creating pages in the background prematurely (before the editor ultimately decides to “save” the page).

I would better do this with hooks, don’t I? :thinking: