In Symfony 2.8/3.0 this has changed a bit and if you have a form that you want to bind other entities to then see my answer here:
Passing data to buildForm() in Symfony 2.8/3.0
In case anyone is using a createNamedBuilder
or createNamed
functions from form.factory
service here's the snippet on how to set and save the data using it. You cannot use the data
field (leave that null) and you have to set the passed data/entities as $options
value.
I also incorporated @sarahg instructions about using setAllowedTypes()
and setRequired()
options and it seems to work fine but you first need to define field with setDefined()
Also inside the form if you need the data to be set remember to add it to data
field.
In Controller I am using getBlockPrefix
as getName
was deprecated in 2.8/3.0
Controller
/*
* @var $builder Symfony\Component\Form\FormBuilderInterface
*/
$formTicket = $this->get('form.factory')->
createNamed(
$tasksPerformedForm->getBlockPrefix(),
TaskAddToTicket::class,
null,
array(
'ticket' => $ticket
)
);
Form
public function configureOptions(OptionsResolver $resolver) {
$resolver->setDefined('ticket');
$resolver->setRequired('ticket');
$resolver->addAllowedTypes('ticket', Ticket::class);
$resolver->setDefaults(array(
'translation_domain'=>'AcmeForm',
'validation_groups'=>array('validation_group_001'),
'tasks' => null,
'ticket' => null,
));
}
public function buildForm(FormBuilderInterface $builder, array $options) {
$this->setTicket($options['ticket']);
//This is required to set data inside the form!
$options['data']['ticket']=$options['ticket'];
$builder
->add('ticket', HiddenType::class, array(
'data_class'=>'acme\TicketBundle\Entity\Ticket',
)
)
...
}