Symfony 2 Form with select list Symfony 2 Form with select list symfony symfony

Symfony 2 Form with select list


Not sure if you found an answer yet but I just had to do some digging around to figure this out for my own project.

The form class isn't set up to use Doctrine like the controller is so you can't reference the Entity the same way. What you want to do is use the entity Field Type which is a special choice Field Type allowing you to load options from a Doctrine entity as you are trying to do.

Ok so long story short. Instead of doing what you are doing to create the choice field, do this:

->add('category', 'entity', array(    'class' => 'VendorWhateverBundle:Category',    'query_builder' => function($repository) { return $repository->createQueryBuilder('p')->orderBy('p.id', 'ASC'); },    'property' => 'name',))

I'm not sure if you could place the query_builder function into a repository or what, I'm kind of swinging wildly as I go. Up to this point the documentation I linked to above is pretty clear on what to do. I guess the next step is to read up on Doctrine's QueryBuilder.

While you're in there I think you want to drop the bit where you are embedding the Classroom form,

->add('classroom', new ClassroomType())

You probably don't want people creating their own classrooms. Unless you do, then yeah.


If the entities are mapped, this is a clean solution for Symfony 2.8+ or 3+

<?phpnamespace My\AppBundle\Form\Type;use My\AppBundle\Entity\Student;use Symfony\Component\Form\AbstractType;use Symfony\Component\Form\FormBuilderInterface;use Symfony\Component\OptionsResolver\OptionsResolver;class StudentType extends AbstractType{    /**     * {@inheritdoc}     */    public function buildForm(FormBuilderInterface $builder, array $options)    {        $builder            ->add('name')            ->add('surname')            ->add('age')            /*             * It will be resolved to EntityType, which acts depending on your doctrine configuration             */            ->add('classroom');    }    /**     * {@inheritdoc}     */    public function configureOptions(OptionsResolver $resolver)    {        $resolver->setDefaults(['data_class' => Student::class]);    }}