Symfony semantic configuration – require different fields based on type

Let’s assume the following example config:

people:
    alice:
        type: employee
        nick: SuperAlice
        department: accounting
    bob:
        type: guest
        nick: HappyBob

The semantic config will look similar to:

->arrayNode('people')
    ->arrayPrototype()
        ->children()
            ->scalarNode('type')->isRequired()->end()
            ->scalarNode('nick')->defaultNull()->end()
            ->scalarNode('department')->end() // should be req. for type=employee only
        ->end()
    ->end
->end()

The employee should be conditionally required based on type

How do I approach that? Additionally the field department should not be valid for other types to improve discoverability.
This problem becomes even bigger when you configure very distinct blocks (e.g. imagine configuring database backends where most of the fields are different between types). I looked at monolog-bundle but it doesn’t offer any clue.

Source: Symfony Questions

Was this helpful?

0 / 0

Leave a Reply 0

Your email address will not be published. Required fields are marked *