Symfony 2 Form with select list

前端 未结 2 1541
陌清茗
陌清茗 2020-12-25 08:27

How can i create a select list with values from a database table in Symfony 2?

I have 2 entities: Student and Classroom with a Many

2条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-25 09:26

    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.

提交回复
热议问题