10

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?

4
  • 1
    You can use form events for this: symfony.com/doc/current/components/form/form_events.html Commented Jan 12, 2016 at 9:45
  • 3
    In your formType I think you can do $entity = $builder->getData() Commented Jan 12, 2016 at 10:05
  • @Put12co22mer2 thats it - works fine! Commented Jan 12, 2016 at 10:11
  • @cklm but if you want to change the form configuration based on the entity, you should still use the event system, so you can get strange errors. Commented Jan 12, 2016 at 13:44

1 Answer 1

6

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(),
));
Sign up to request clarification or add additional context in comments.

1 Comment

Works for me, thanks you so much, I did not remember how to change the default options!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.