Map select INT with String in Global.php?

In my application the user has to choose several formselects and these return an INT (after jugling). I want to save this INT in the database. For example province in one of my forms:

 $this->add([
        'name' => 'provincie',
        'type' => Select::class,
        'options' => [
            'label' => 'Provincie',
            'empty_option' => 'Kies uw provincie',
            'value_options' => [
                1 => 'Friesland',
                2 => 'Groningen',
                3 => 'Drenthe',
                4 => 'Overijsel',
                5 => 'Flevoland',
                6 => 'Gelderland',
                7 => 'Utrecht',
                8 => 'Noord-Holland',
                9 => 'Zuid-Holland',
                10 => 'Zeeland',
                11 => 'Noord-Braband',
                12 => 'Limburg'
            ],
        ],
     ]);

But if I have to display the user (after a database select) then obviously not the INT should be shown, but the associated name (string).
Is it better to use a mapping table or an array based on which the INT can be mapped with the string (and can also be used in the selects).
I’m leaning towards the array but where to store it as it is used throughout the application. Is global.php the place? And if so, how to get this array into a model or controller?

Well, there is a few questions that come to mind.

  1. Are you going to need to change those value_options programmatically?
  2. Is this to be used in more than 1 given form?
  3. Will you ever need to translate them?

As far as how to represent them programmatically. In your code, if the do not need to be edited programmatically I suppose I would suggest a Backed Enum if your php version supports it.

If you want to store them in config then I would suggest storing them under a key matching the class name that consumes them. For instance:

//... config
YourFormClass::class => [
                'value_options' => [
                    'option1' => 'value1',
                    'option2' => 'value2',
                ],
            ],
// ... config

Then in your form factory you can pull the form related config from the config service.

$formConfig = $container->get('config')[YourFormClass::class] ?? [//some defaults?];

How you code it is really up to you.

As for storing the selected values in the db. If you db supports it and those options will not change then I would probably go with enum.

1 Like