Render classes in PHP but show color swatches in panel

Is it possible to have this in the yml:

fields:
  backgroundcolor:
    type: color
    mode: options
    options:
      - "#f8b195"
      - "#f67280"
      - "#c06c84"
      - "#6c5b7b"
      - "#355c7d"

But in the php I want to render classes that are tied in to each color.
Is that possible and if yes how would I do that?

See “Custom values and labels” in Color | Kirby CMS

You could define the colors and their classes in your config:

return [
    'my' => [
        'colors' => [
            [
                'name' => 'Color A',
                'class' => 'color-a',
                'hex'   => '#3e3e3e',
            ],
            [
                'name' => 'Color B',
                'class' => 'color-b',
                'hex'   => '#aaa',
            ],
            [
                'name' => 'Color C',
                'class' => 'color-c',
                'hex'   => '#ddd',
            ]
        ]
    ]
];

And then use the hex and name fields in the panel:

myColorField:
  type: color
  options:
    type: query
    query: kirby.option('my.colors')
    text: "{{ item.name }}"
    value: "{{ item.hex }}"

And in your templates you could retrieve the array of colors with $kirby->option('my.colors') and then match the one from the page’s field:

$hex = $page->content()->get('myColorField')->value;
$colors = $kirby->option('my.colors');
$color = array_find(
  $colors,
  fn($color) => $color['hex'] == $hex
);
var_dump($color['class']);

Hi thanx for you answer so far.
I have a follow up. I am using my kirby setup as a boilerplate and per project I swap only the css folders. That way all style related stuff is only in the assets folder.

Is there anyway to not have these colors listed in the php? That would make it allot easier because in multiple projects and can keep the config the same

You’ll need to have the colors as PHP values if you want to render a color picker with options. Otherwise you can just have a Select field with names like “color 1”, “color 2”, etc., but users of the Panel will have no idea what the colors look like.

You could define the colors in JSON or YAML and load that data using PHP, and also use the same data to generate the corresponding CSS. But that’s maybe harder than having it directly in PHP.

If you have this data in PHP, you could always render a HTML <style> element based on that, for example as CSS variables:

<style>
:root {
<?php foreach($kirby->option('my.colors') as $color): ?>
  <?= $color['prop'] ?>: <?= $color['hex'] ?>;
<?php endforeach ?>
}
</style>

Thanx for you help!

If you have multiple projects, you can import specific other php files into your main config, so while the main config remains the same, what you import for each can be different.

See here for an example of modular config data: getkirby.com/site/config at main · getkirby/getkirby.com · GitHub

Awesome! Thanx for the tip