Symfony 2 形式 +显示关系中的数据
我正在使用 Symfony 2 和原则。我目前有一个名为 Worker 的实体,并且在 Worker 实体中与 User 实体存在多对一关系。
/**
* @ORM\ManyToOne(targetEntity="User")
* @ORM\JoinColumn(name="user_id", referencedColumnName="id")
*/
private $user;
还有更多的实体,例如 Worker 以及 Manager 等。我想创建一个用于创建 Job 实体的表单。在表单中,我尝试创建一个选择工人的选择选项,但工人的姓名存储在用户数据库中。有没有办法在表单选项中从用户数据库中打印工人的姓名。
$builder->add('workers','entity', [
'label' => 'Workers:',
'property' => 't.user.firstName',
'empty_value' => 'Choose a Worker',
'class' => 'Company\CompanyBundle\Entity\Worker',
'query_builder' => function (\Company\CompanyBundle\Repository\WorkerRepository $repository) {
return $repository->createQueryBuilder('t')
->add('orderBy', 't.user.firstName ASC');
}
]);
有什么想法吗?
I am using Symfony 2 with doctrine. I currently have an entity called Worker and in the Worker entity there is a Many To One relationship with a User entity.
/**
* @ORM\ManyToOne(targetEntity="User")
* @ORM\JoinColumn(name="user_id", referencedColumnName="id")
*/
private $user;
There are more entities like Worker as well such as Manager and such. I want to create a form that creates a Job entity. In the form I am trying to create a select option that selects a Worker, but the worker's name is stored in the user database. Is there any way to print the worker's name from the user database in the form options.
$builder->add('workers','entity', [
'label' => 'Workers:',
'property' => 't.user.firstName',
'empty_value' => 'Choose a Worker',
'class' => 'Company\CompanyBundle\Entity\Worker',
'query_builder' => function (\Company\CompanyBundle\Repository\WorkerRepository $repository) {
return $repository->createQueryBuilder('t')
->add('orderBy', 't.user.firstName ASC');
}
]);
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为做这样的事情就足够了:
此外,您应该在您的 Worker 实体中实现一个“__toString()”方法,您将在其中返回您想要显示的任何内容(在本例中为工作人员名称),因此您的Worker 实体中的 __toString 方法是这样的:
这是我通常实现这种关系的方式,我希望它有帮助!
I think that it would be enoough to do something like this:
Besides, you should implement a "__toString()" method in your Worker entity where you would return whatever you want to show (in this case, the worker name), so your __toString method in the Worker entity would be something like this:
It's the way I usually implement this kind of relations, I hope it helps!
如果您愿意,您可以执行其他选项:
如果您定义了选项“property”,则不需要在实体类中实现“_toString()”
If you prefer, you could do this other option:
If you defined the option "property" you don't need implement the "_toString()" in the entity class