15

I'm trying to define a Configuration object. I have successfully defined an array prototype node (like security.firewalls). My prototye array has an required element but I want to allow arbitrary parameters to be added to each array if needed.

My question is, how can I allow extra, undefined elements to be added to each prototype array?

Here's my config:

acme_widget:
    handlers:
        handler_one:
            service: handler.one.service
        handler_two:
            service: handler.two.service
            extra_array:
                - Extra 1
                - Extra 2
            extra_scalar: Extra 3

Here's my class builder:

    /**
     * Generates the configuration tree.
     *
     * @return TreeBuilder
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder;
        $rootNode = $treeBuilder->root('acme_widget');

        $rootNode
            ->children()
                ->arrayNode('handlers')
                    ->useAttributeAsKey('service')
                    ->prototype('array')
                        ->children()
                            ->scalarNode('service')->isRequired()->end()
                            ->booleanNode('enabled')->defaultTrue()->end()
                        ->end()
                    ->end()
                ->end()
            ->end()
        ;

        return $treeBuilder;
    }

I'm getting "InvalidConfigurationException: Unrecognized options".

1
  • An alternative is to call ->ignoreExtraKeys(false) on the ->prototype('array'). Commented Dec 20, 2016 at 14:54

1 Answer 1

22

I would just add a variable (can contain anything) node "extra":

->scalarNode('service')->isRequired()->end()
->booleanNode('enabled')->defaultTrue()->end()
->variableNode('extra')->end()

Your config would then look like:

acme_widget:
    handlers:
        handler_one:
            service: handler.one.service
        handler_two:
            service: handler.two.service
            extra:
                array:
                    - Extra 1
                    - Extra 2
                scalar: Extra 3
Sign up to request clarification or add additional context in comments.

1 Comment

variableNode() is exactly what I was looking for, thanks. Too bad it's missing from symfony docs :(

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.