形式上的一对一关联?
在symfony 2.0中,如何使用表单中的一对一关联创建下拉列表?你们能举个很好的例子吗?
In symfony 2.0, how to create a drop down list using one-to-one association in form? Can you guys put good example please?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我会尽力以我理解的方式回答你的问题。假设我有一个绑定到单个大学对象的
Faculty
对象。因此,在用于创建或编辑教师的表单中,我显示数据库中所有大学的组合框,用户可以从中选择一所。有一种特殊的 Symfony 字段类型可以做到这一点:实体类型。下面是我在用于创建教师表单的FacultyType
对象中使用的buildForm
方法的代码:注意:还可以为实体字段设置其他属性类型,我邀请您查看此页面有关它的更多信息。
渲染后,这将显示一个组合框,其中包含我在数据库中设置的所有大学。当用户保存表单时,选择的大学将被分配给通过设置器绑定到表单的教员对象。您可能可以呈现一个下拉列表而不是组合框。如果您需要选择多个实体,字段类型实体的
'multiple'
选项可能会很有用。话虽这么说,我展示的示例不是一对一关系,而是
Faculty
对象的多对一关系和University< 的一对多关系。 /代码> 对象。一对一关系更像是
大学
具有唯一地址
的关系。在这种情况下,组合框不会有用,因为大学只能有一个地址,因此子表单会更合适。如果它有多个地址,那么它就成为一对多的关系,就像大学与其院系之间的关系一样。不确定这是否能正确回答您的问题,但我希望它能引导您找到最终的解决方案。
问候,
马特
I will try to answer your question the way I understand it. Let's say I have a
Faculty
object bound to a singleUniversity
object. So in the form used to create or edit a faculty, I display a combo box of all the university in the database and the user choose one among them. There is one special Symfony field type that does exactly this: the entity type. Below is the code of thebuildForm
method that I use in myFacultyType
object used to create the faculty form:Note: There are other properties that can be set for the entity field type, I invite you to take a look at this page for more information on it.
Rendered, this will show a combo box with all the universities I have set in the database. When the user save the form, the university chose is assigned to the faculty object bound to the form via a setter. You could probably render a drop-down list instead of a combo box. If you need to select multiple entities, the
'multiple'
option of the field type entity could be useful.This being said, the example I showed is not a One-to-One relation but rather a Many-to-One for the
Faculty
object and a One-to-Many for theUniversity
object. A One-to-One relation would be something more like a relation where aUniversity
has a uniqueAddress
. In this case, a combo box wouldn't be useful since the university can only have one adress so a sub-form would be more appropriate. If it has many adresses, then it becomes a One-to-Many relation like the relation between the university and its faculties.Not sure if this will answer your question correctly but I hope it will lead you to a final solution.
Regards,
Matt
您需要使用Symfony2中的实体字段类型。一个很好的例子可以在 http://symfony.com/doc/current 找到/reference/forms/types/entity.html
You need to use the entity field type in Symfony2. A good example is found at http://symfony.com/doc/current/reference/forms/types/entity.html