B
B
BoShurik2015-07-06 17:44:08
symfony
BoShurik, 2015-07-06 17:44:08

TreeBuilder. How to describe an associative array with scalar values?

Hello!
There is the following config:

app:
    search:
        files:
            AppBundle\Entity\Page\Page\Content:
                - content
            AppBundle\Entity\Page\News:
                - content
                - file

How to describe it in TreeBuilder to get a similar structure?
array (size=2)
  'AppBundle\Entity\Page\Page\Content' => 
    array (size=1)
      0 => string 'content' (length=7)
  'AppBundle\Entity\Page\News' => 
    array (size=2)
      0 => string 'content' (length=7)
      1 => string 'file' (length=4)

At the moment it turned out to be done as follows:
$rootNode
    ->children()
        ->arrayNode('search')
            ->children()
                ->arrayNode('files')
                    ->beforeNormalization()->always(function($values){
                        $result = array();
                        foreach ($values as $class => $fields) {
                            $result[$class]['fields'] = $fields;
                        }

                        return $result;
                    })->end()
                    ->prototype('array')
                        ->children()
                            ->arrayNode('fields')->prototype('scalar')->end()
                        ->end()
                    ->end()
                ->end()
            ->end()
        ->end()
    ->end()
;

But at the output we get:
array (size=2)
  'AppBundle\Entity\Page\Page\Content' => 
    array (size=1)
      'fields' => 
        array (size=1)
          0 => string 'content' (length=7)
  'AppBundle\Entity\Page\News' => 
    array (size=1)
      'fields' => 
        array (size=2)
          0 => string 'content' (length=7)
          1 => string 'file' (length=4)

Thanks in advance.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
keltanas, 2015-07-07
@BoShurik

Try

$rootNode
    ->children()
        ->arrayNode('search')
            ->children()
                ->arrayNode('files')
                    ->beforeNormalization()->always(function($values){
                        $result = [];
                        foreach ($values as $class => $fields) {
                            $result[$class] = $fields;
                        }
                        return $result;
                    })->end()
                    ->prototype('array')
                       ->prototype('scalar')->end()
                    ->end()
            ->end()
        ->end()
    ->end()
;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question