问题描述
如何在 Symfony 2 中使用数据库表中的值创建选择列表?
How can i create a select list with values from a database table in Symfony 2?
我有 2 个实体:Student 和 Classroom 具有多对一关系,我需要创建一个包含以下字段的表单:name,姓、年龄、教室(从可用课程中选择列表).
I have 2 entities: Student and Classroom with a ManyToOne relationship and i need to create a form with the folowing fields: name, surname, age, classroom(select list from available classes).
在我的学生表格中我有
$builder
->add('name')
->add('surname')
->add('age')
->add('classroom', new ClassroomType())
;
在我的课堂表格中,我有这个:
$classrooms =$this->getDoctrine()->getRepository('UdoCatalogBundle:Classroom')->findAll();
$builder
->add('clasa','choice',array('choices' => array($classrooms->getId() => $classrooms->getName())));
我收到以下错误:
Fatal error: Call to undefined method UdoCatalogBundleFormClassroomType::getDoctrine() in /var/www/html/pos/src/Udo/CatalogBundle/Form/ClassroomType.php on line 13
亲切的问候,卡瑙丹
推荐答案
不确定你是否找到了答案,但我只需要四处挖掘才能为我自己的项目解决这个问题.
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.
表单类没有设置为像控制器那样使用 Doctrine,因此您不能以相同的方式引用实体.您要做的是使用 entity Field Type 这是一个特殊的选择 Field Type允许您在尝试时从 Doctrine 实体加载选项.
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',
))
我不确定您是否可以将 query_builder 函数放入存储库中,或者什么,我在走的时候有点摇摆不定.到目前为止,我上面链接到的文档非常清楚该怎么做.我想下一步是阅读 Doctrine 的 QueryBuilder.
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.
这篇关于带有选择列表的 Symfony 2 表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!