I have 3 form types in symfony2
FaultType which is the parent of all next collections
<?php
namespace My\FaultBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;
class FaultType extends AbstractType
{
public function buildForm(FormBuilder $builder, array $options)
{
$builder
->add('title')
->add('steps', 'collection', array(
'type' => new StepType(),
'allow_add' => true,
'prototype' => true,
'by_reference' => false,
))
->add('created')
->add('updated')
;
}
public function getDefaultOptions()
{
return array(
'data_class' => 'My\FaultBundle\Entity\Fault'
);
}
public function getName()
{
return 'my_fault_fault';
}
}
StepType:
<?php
namespace My\FaultBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;
class StepType extends AbstractType
{
public function buildForm(FormBuilder $builder, array $options)
{
$builder
->add('body')
->add('photos', 'collection', array(
'type' => new PhotoType(),
'allow_add' => true,
'allow_delete' => true,
'prototype' => true,
'by_reference' => false,
))
;
}
public function getDefaultOptions()
{
return array(
'data_class' => 'My\FaultBundle\Entity\Step'
);
}
public function getName()
{
return 'my_fault_step';
}
}
and the last PhotoType:
<?php
namespace My\FaultBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;
class PhotoType extends AbstractType
{
public function buildForm(FormBuilder $builder, array $options)
{
$builder
->add('name')
->add('description')
->add('filename')
;
}
public function getDefaultOptions()
{
return array(
'data_class' => 'My\FaultBundle\Entity\Photo'
);
}
public function getName()
{
return 'my_fault_photo';
}
}
I found excelent article link about prototype, and with one nested form type is very good, but I have a problem when a want to get this to work with third nest mean PhotoType... Photos are in collection of Steps, which is collection of Fault..., how can I achive dynamically add/remove photos for steps with this example...?
I made a JS snippet that can be of help here. you just have to add two buttons [add new, delete last]. https://gist.github.com/juanmf/10483041
it can handle recursive/nested prototypes. It's coupled with a mediator (same as Symfony event Dispatcher) that allows you to bind generated controls to events. If you dont need the mediator delete these lines:
docdigital.mediatorInstance.send(
docdigital.constants.mediator.messages.clonePrototype_prototypeAdded,
$clone
);
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