Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to embed a precharged collection of non-entity forms in symfony2

I want to embed a collection of precharged non-entity forms, here is the code, first is the parent form buildForm method.

public function buildForm(FormBuilderInterface $builder, array $options) {
    $builder->add("example1")->add("example2");
    $builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
        /*some logic to do before adding the collection of forms*/
        $form->add('aclAccess', 'collection', array(
            'type' => new ChildFormType(),
            'allow_add' => true,
            'mapped' => false,
            'data' => /* I dont know how to precharge a collection of non-entity forms*/
        ));
    });
}

now the child form

public function buildForm (FormBuilderInterface $builder, array $options) {
    $builder->add("test1", "text", array("read_only" => true, "data" => "test"));
    $builder->->add("test2", "choice", array(
        'choices'   => array('opt1' => 'Opt1', 'opt2' => 'Opt2'),
        'multiple'  => true,
        'expanded'  => true
    ));
}

so basicly i want to manage those child options in the test2 field as separated forms, each option group will depend on the value of the test1 field, i know this can be done by coding everythin in twig without form classes but i think having form classes its the best practice to run phpunit test, for maintainability, etc ...

like image 205
metalvarez Avatar asked Nov 01 '13 15:11

metalvarez


1 Answers

Per the documentation on Using a Form Without a Class, the bound data is just an array.

If you don't do either of these, then the form will return the data as an array. In this example, since $defaultData is not an object (and no data_class option is set), $form->getData() ultimately returns an array.

And to clear up any misconception you might have about form data - the underlying object/class of a form type does not have to be an Entity - you can use any class with public properties or getters/setters that map to the form fields. For that matter, Entity classes are nothing special themselves - they just have a bunch of mapping information that tells the ORM how to persist them.

But, back to your original question, I don't know what your ChildFormType looks like, but let's assume it has two fields, sequence and title

    $form->add('aclAccess', 'collection', array(
        'type' => new ChildFormType(),
        'allow_add' => true,
        'mapped' => false,
        'data' => array(
            array('sequence' => 1, 'title' => 'Foo')
          , array('sequence' => 2, 'title' => 'Bar')
        )
    ));

That should do the trick

like image 127
Peter Bailey Avatar answered Nov 12 '22 11:11

Peter Bailey