Build a form having a checkbox for each entity in a doctrine collection

前端 未结 3 574
长情又很酷
长情又很酷 2020-12-01 11:35

I\'m displaying an html table for a filtered collection of entities and I want to display a checkbox in each row as part of a form which will add the selected entities to a

相关标签:
3条回答
  • 2020-12-01 12:01

    If someone is looking for solution for Symfony >=2.3

    You have to change this:

        $data = $form->getData();
        $ids  = array();
        foreach ($data['foo_id'] as $entity) {
            $ids[] = $entity->getId();
        }
    

    to this:

        $data = $form['foo_id']->getData();
        $ids = array();
        foreach ($data as $entity) {
            $ids[] = $entity->getId();
        }
    
    0 讨论(0)
  • 2020-12-01 12:03

    I create a symfony bundle for render a collection of entities as a checkbox table in a configurable way. Although it has been a while since this question was asked, I hope this can help others with this same kind of problem.

    0 讨论(0)
  • 2020-12-01 12:11

    I think this will answer your question.

    Forget the FooEntitySelectionType. Add a property_path field option to FooEntitySelectByIdentityType and set the data_class option to null:

    class FooEntitySelectByIdentityType extends AbstractType
    {
        public function buildForm(FormBuilderInterface $builder, array $options)
        {
            $builder->add('foo_id', 'entity', array(
                'required'      => false,
                'class'         => 'MeMyBundle:FooEntity',
                'property'      => 'id',
                'property_path' => '[id]', # in square brackets!
                'multiple'      => true,
                'expanded'      => true
            ));
        }
    
        public function setDefaultOptions(OptionsResolverInterface $resolver)
        {
            $resolver->setDefaults(array(
                'data_class'      => null,
                'csrf_protection' => false
            ));
        }
    
    # ...
    

    and in your controller, build the FooEntitySelectByIdentityType:

    $form = $this
        ->createForm(
            new \Me\MyBundle\Form\Type\FooEntitySelectByIdentityType,
            $collection_of_foo
        )
        ->createView()
    ;
    

    and then in the controller action which receives the POSTed data:

    $form = $this
        ->createForm(new \Me\MyBundle\Form\Type\FooEntitySelectByIdentityType)
    ;
    $form->bind($request);
    if ($form->isValid()) {
        $data = $form->getData();
        $ids  = array();
        foreach ($data['foo_id'] as $entity) {
            $ids[] = $entity->getId();
        }
        $request->getSession()->set('admin/foo_list/batch', $ids);
    }
    

    and finally, in your twig template:

    {# ... #}
    {% for entity in foo_entity_collection %}
        {# ... #}
    
        {{ form_widget(form.foo_id[entity.id]) }}
    
        {# ... #}
    
    0 讨论(0)
提交回复
热议问题