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).
My first idea was to create a single form but it seems difficult to combine several instances in a single form.
I also considered to create a form per row, but this means every line would have its own "submit" field, and it would be impossible to save changes in more than one row at once.
In Symfony's doc I've seen a topic about form collections but I don't know if this is something I can use, since the instances of my entity are completely independant.
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 !
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With