Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony3: Construct FormType

Tags:

php

symfony

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?

like image 868
cklm Avatar asked Jan 12 '16 09:01

cklm


1 Answers

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(),
));
like image 150
Yassine Guedidi Avatar answered Nov 16 '22 02:11

Yassine Guedidi