ibi0tux
ibi0tux

Reputation: 2629

Creating a grid of forms in Symfony 2

I'm working on a page on which I would like to render an entity's instance as phpMyAdmin would do for instance.

More specifically, I would like to get a table in which columns are fields of the entity and rows are all the instances of this entity, and make all values (except id) editable, and save them to database.

My problem is I don't really know what is a good practice to do that and what is possible with Symfony (I'm quite new with this framework).

Well, I think I'm not the first wanting to do that, but I was unable to find any way to do it, maybe am I missing something ?

Any advice is welcomed, thanks !

Upvotes: 7

Views: 2066

Answers (1)

João Alves
João Alves

Reputation: 1941

Doing "à là symfony" you could create a Base Form, for example AllRowsType that has a field of Type collection, and each one of the rows is of Type RowType:

public function buildForm(FormBuilderInterface $builder, array $options)
    {

        $builder               
            ->add('rows', 'collection', array(
                'type'   => new RowType(),
                'allow_add' => false,
                'allow_delete' => false,
                'by_reference' => false
             ));
    }

Then your RowType will be a normal form for your entity.

class RowType extends AbstractType {
    public function buildForm(FormBuilderInterface $builder, array $options)
    {

       $builder               
            ->add('name', 'text');
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Acme\Bundle\DemoBundle\Entity\Row',
        ));
    } }

The validations can be on your RowType like a normal form, but if you have problems, you can set cascade_validation => true on the default options of your AllRowsType.

To iterate each RowType in twig you can do:

{% for row in form.rows%} {{ form_row(row.name) }} {% endfor %}

On twig in order to get the ID of each row entity you can do:

{{ row.vars.value.id }}

On Controller, you can do $allrowsForm->get('rows')->getData() and you have an ArrayCollection of Row Entities and do whatever you want.

You can read http://symfony.com/doc/current/cookbook/form/form_collections.html for how to handle a collection of forms.

Upvotes: 4

Related Questions