Adding Random Class from Field

Hey folks,

I have a .card class that I use in a number of places across site, and coupled with that class is always a colour. For example, I would have:

<div class="card yellow">
...
</div>

Where needed, the colour is usually chose from a drop-down menu within my blueprints, so I have something like:

<div class="card <?= $child->colour() ?>">

The problem here is that I always have to choose the card colour manually. I would like for Kirby to set a random value from the options within the colour dropdown field when I create the page. I’ve tried changing my template to this, but it had no effect:

<div class="card <?= $child->colour()->shuffle()->first() ?>">

Can anyone help please?

Just to clarify: You want to assign a random value in the template/snippet that changes every time to load the page, not assign a fixed random default value when the page is created?

Sorry I wasn’t clear. It’s the latter - I want the value to be selected once, then stay static.

So when the page is created, it selects one of 5 colour options at random, then sticks with it.

It would be easier if Kirby supported query language for the default option out of the box, but that isn’t the case.

So to make this you have two options:

  1. The easy way: Use a page.create:after hook and update the page within the hook. You can either hard-code your array of options into the hook code, or you read the options from the blueprint (see Using blueprints in the frontend | Kirby CMS). Maybe I should add that you cannot use the shuffle() method on an array, but have to resort to A::shuffle.

  2. Or you create a custom color field and overwrite the default method, like in the examples here: Dynamic default number field - #2 by texnixe. Not much more difficult and you only need to do this once and can reuse it in other parts if needed without having to adapt any hooks.

Thanks Sonja. I’ll give it a try tomorrow and will post back here.