Random field default


in my template I have a per article setting for the display style ranging from 1-6. I would like add this as a field to the panel entry, however select a random default at the beginning.
Right now I have this:

label: Style
type: select
default: random
1: 1

6: 6

However to my surprise it did not work;-) any ideas?


No, random is not an option, I’m afraid. If you want a default value, you have to decide which one it should be.

If you really need this, you could use an API in a query and generate the order of the options randomly. If the field is then required, the first option should be activated automatically.

See: https://getkirby.com/docs/cheatsheet/panel-fields/select (Dynamic options via JSON API)

Thanks for the answer! I was able to accomplish it in the template itself:

<?php srand(hash("sha256", $p->title())); ?>
<article class="<?php e($p->style()->isNotEmpty(), "style" . $p->style(), "style". rand(1,6) ) ?>">


While that definitely works, it is probably not very elegant in terms of performance. Recalculating the hash every time can add up.

You could use a Panel hook that randomizes the style on creation of the page. If the value hasn’t been set manually by the user, it would then be set to the random value.

PS: Please use Markdown code blocks when posting code. They use three backticks at the beginning and end. I have changed it above.

Would this be the correct hook?
Would it save automagically?

kirby()->hook('panel.page.create', function($page) {
    srand(hash("sha256", $page->title()));
    $page->style() = rand(1,6);

Not quite, it has to be like this:

kirby()->hook('panel.page.create', function($page) {
    if($page->style()->empty()) $page->update(array('style' => rand(1, 6)));

You don’t need to seed the random number generator however since “any random number” is random enough here. It doesn’t have to be the same one each time since it is generated only once anyway.

1 Like