Nested form in Symfony

2019-08-23 15:03发布

I have a nested entity like this:

<?php
/**
 * @ORM\Entity(repositoryClass="App\Repository\BinderRepository")
 */
class Binder
{
/**
 * @ORM\Id
 * @ORM\GeneratedValue
 * @ORM\Column(type="integer")
 *
 * @Groups({"export"})
 *
 * @var int
 */
private $id;

/**
 * @ORM\Column(type="string", length=125)
 *
 * @Groups({"export"})
 *
 * @var string
 */
private $name;

/**
 * @ORM\ManyToMany(targetEntity="App\Entity\Binder")
 *
 * @Groups({"export"})
 * @MaxDepth(10)
 *
 * @var Collection
 */
private $children;

So, a Binder can contain a subBinder which can contain a subsubBinder etc.

I export these entities in JSON, modify them in front-end and re-post them in JSON.

I'd like to make a form which will be able to handle this kind of submission:

[{"name":"Root 1","id":1,"level":0,"is_open":true,"children":[{"name":"Child 1","id":2,"level":1}]}]

So, I've built this form:

class BinderType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('name', TextType::class, ['label' => 'binders.name'])
        ->add('children', CollectionType::class, array(
        'entry_type'          => BinderType::class,
        'allow_add'     => true))
        ->add('create', SubmitType::class, ['label' => 'binders.create'])
    ;
}

public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults([
        'data_class' => Binder::class,
    ]);
}
}

But unfortunately, it throws a Maximum function nesting level of '256' reached, aborting!

I know it's because I'm creating a form with infinite subchilds, but I just want to handle the JSON I'm submitting which is currently 2 levels (root and subNode). I can limit the nesting to 10 levels but I just like my form to work.

What am I missing ?

1条回答
再贱就再见
2楼-- · 2019-08-23 15:10

Add a recursion limit. Anyway you will need to increase the nesting level on your php.ini for symfony projects I've found 256 it is a quite low level for many of my projects.

class BinderType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('name', TextType::class, ['label' => 'binders.name'])
            ;
        if ($options['recursion']>0) {
            $builder
                ->add('children', CollectionType::class, array(
                    'entry_type' => BinderType::class,
                    'allow_add' => true,
                    'entry_options' => ['recursion'=>$options['recursion']-1]
                ))
            ;
        }


    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => Binder::class,
            'recursion' => 10
        ]);
    }
}
查看更多
登录 后发表回答