I have a form in Symfony3, which I initialize - following the docs - as followed:
$form=$this->createForm(BookingType::class,$booking);
$booking is an already existing entity, which I want to modify - but I want to modify the form depending on the entity - like:
public function buildForm(FormBuilderInterface $builder,$options) {
$builder->add('name');
if(!$this->booking->getLocation()) {
$builder->add('location');
}
}
Prior Symfony 2.8 it was possible to construct the FormType like:
$form=$this->createForm(new BookingType($booking),$booking);
Which is exactly what I want :) But in Symfony3 this method throws an exception. How can I pass an entity to my formtype?
You can also change a form type based on custom options.
In the form type:
public function buildForm(FormBuilderInterface $builder, $options) {
$builder->add('name');
if($options['localizable']) {
$builder->add('location');
}
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'localizable' => true,
));
}
In the controller:
$form = $this->createForm(BookingType::class, $booking, array(
'localizable' => !$booking->getLocation(),
));
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