Select field with optgroup

Hello every one,
I want to make a select field with optgroup.

I started a new plugin on GitHub - marc31/kirby-selectoptgroup: Small Kirby CMS pluggin to create select input with optgroup

It could be answer to Quick question regarding subsections in Select fields

For this I try to add a new field to a $page from the ‘save’ hook (look at the index.php)
but I don’t manage to add field in this hook do you have some clue ?

Thanks

I don’t really understand what your are trying to achieve with this save method? The plugin seems to work as expected without it?

Yes this first version work.
But it’s not perfect for filtering. I mean if I would get all apple types I have to do :

page('MYPAGE')->children()->listed()->filterBy('fruits', '^=', 'apple-')

But if I would get all apple and pear I need to use custom function for filtering.
I was wondering if I can improve plugin by splitting field in content
For example in the content file I would like to have :

----

Test: apple

----

Test-apple: granny_smith

That’s why I would add some field programmatically when user save the select selectoptgroup
I try

But I don’t find how to save the new field into the current page.

On discord @distantnative make a good suggestion

I would instead suggest a custom collection filter:

Kirby\Toolkit\Collection::$filters['^= in'] = [
  'validator' => function ($value, $test) {
    foreach ($test as $t) {
      if (V::startsWith($value, $t) === true) {
        return true;
      }
    }
    return false;
  },
  'strict' => false
];

And then you could do :

$page->children()->listed()->filterBy('fruits', '^= in', ['apple-', 'pear-'])

Without custom collection filter, you could also do something like

page('MYPAGE')
  ->children()
  ->listed()
  ->filterBy('fruits', 'in', ['apple', 'pear'], '-')

(notice however that @distantnative’s solution is both more accurate and faster)

@rasteiner thanks it working !

I will add the code from @distantnative and some docs