How to change the shape of Symfony2 based on the value of the field selected by the user?

I have a Blog type, and I want certain fields to be added to the form only if the user makes a specific selection in the selection field. I heard about EventListener, but I don't think there is a FormEvent that I can subscribe to so that the listener can track the select event.

How can i achieve this?

This is my BlogType:

namespace Blogger\BlogBundle\Form; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolverInterface; use Blogger\BlogBundle\Form\EventListener\AddAuthorFieldSubscriber; class BlogType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('title') ->add('blog') ->add('category', 'entity', array( 'class' => 'BloggerBlogBundle:Category', 'property' => 'name', ) ->add('onlyifdefaultcategory') ); } public function setDefaultOptions(OptionsResolverInterface $resolver) { $resolver->setDefaults(array( 'data_class' => 'Blogger\BlogBundle\Entity\Blog', 'cascade_validation' => true, )); } public function getName() { return 'blogger_blogbundle_blogtype'; } } 
+4
source share
2 answers

You are right when you say that you need to use an event listener for this. There is a very good article in the Symfony cookbook: Here is the cookbook .

You should check out the “Customizing Your Form Based on Baseline” part.

If you need more information, let us know, but I think the first example is exactly what you need.

+2
source

I think this is only possible using JavaScript. You can create your own type and declare a widget for this type with JS, which makes it possible.

For the shape of the building, here is an example with listeners. Check it out: symfony guide

-1
source

All Articles