我有一个问题--这里是否有可能将AssociationField配置为使用特定属性。即:
我有一个与用户有多对一关系的订阅实体,用户有一个__toString()方法,它返回用户名,它在整个应用程序中使用,所以我不能更改它。在“创建订阅”表单中,我有AssociationField::new(' User '),在那里我可以找到他的名字。
但是这是不方便的,因为当我需要创建订阅时,会弹出许多同名用户。相反,我希望能够通过ID或电子邮件搜索用户。
是否有一种方法可以覆盖默认行为?
发布于 2022-03-03 14:45:39
您的AssociationField
是使用Symfony EntityType制作的。如果您查看此字段使用的表单类型。
//AssociationField.php
public static function new(string $propertyName, $label = null): self
{
return (new self())
//...
->setFormType(EntityType::class)
//...
这意味着你可以使用它的所有选项。在这里见更多。
在您的情况下,通过定义另一个属性或回调来修改您的标签非常容易。
然后可以使用->setFormTypeOption()
修改实体类型选项。
因此,如果要使用回调函数定义自定义标签:
AssociationField::new('user')
->setFormTypeOption('choice_label', function ($user) {
return $user->getEmail();
});
或者使用php 7.4箭头函数:
AssociationField::new('user')
->setFormTypeOption('choice_label', fn($user) => $user->getEmail());
还可以将email属性定义为label:
AssociationField::new('user')
->setFormTypeOption('choice_label', 'email');
https://stackoverflow.com/questions/71338329
复制相似问题