Allowing key-value pairs in Symfony 2 Bundle semantic configuration
You should add useAttributeAsKey('name')
to your billing node configuration in Configurator.php
.
More information about useAttributeAsKey()
you can read at Symfony API Documentation
After changes billing node configuration it should be like:
->arrayNode('billings') ->isRequired() ->requiresAtLeastOneElement() ->useAttributeAsKey('name') ->prototype('scalar')->end()->end()
You may add something like:
->arrayNode('billings') ->useAttributeAsKey('whatever') ->prototype('scalar')->end()
After that keys will magically appear.
I recently had to setup some nested arrays configuration.
Needs were
- A first level array with custom keys (discribing an entity path)
- Each of those arrays had to have one or more arbitrary tags as keys, with boolean value.
To achieve such a configuration, you have to casacade prototype()
method.
So, the following configuration:
my_bundle: some_scalar: my_scalar_value first_level: "AppBundle:User": first_tag: false "AppBundle:Admin": second_tag: true third_tag: false
can be obtained using the following configuration:
$treeBuilder = new TreeBuilder();$rootNode = $treeBuilder->root('my_bundle');$rootNode ->addDefaultsIfNotSet() # may or may not apply to your needs ->performNoDeepMerging() # may or may not apply to your needs ->children() ->scalarNode('some_scalar') ->info("Some useful tips ..") ->defaultValue('default') ->end() ->arrayNode('first_level') ->info('Useful tips here..') # first_level expects its children to be arrays # with arbitrary key names ->prototype('array') # Those arrays are expected to hold one or more boolean entr(y|ies) # with arbitrary key names ->prototype('boolean') ->defaultFalse()->end() ->end() ->end() ->end() ->end();return $treeBuilder;
Dumping $config from inside the extension class gives the following output:
Array( [some_scalar] => my_scalar_value [first_level] => Array ( [AppBundle:User] => Array ( [first_tag] => ) [AppBundle:Admin] => Array ( [second_tag] => 1 [third_tag] => ) ))
And voilĂ !