在 EasyAdmin3 中配置 AssociationField 默认属性

发布于 2025-01-11 20:59:14 字数 276 浏览 5 评论 0原文

我有一个问题 - 是否可以配置 AssociationField 以使用特定属性。即:

我有一个与用户具有多对一关系的订阅实体,用户有一个 __toString() 方法,该方法返回用户名,并且它在整个应用程序中使用,所以我无法更改它。在“创建订阅”表单中,我有 AssociationField::new('user'),我可以在其中通过用户的名字找到用户。

但这很不方便,因为当我需要创建订阅时,会弹出许多同名的用户。相反,我希望能够通过 ID 或电子邮件搜索用户。

有没有办法覆盖默认行为?

I have a question - is here a possibility to configure AssociationField to work with specific property. i.e:

I have a Subscription Entity with a many-to-one relation to User, User has a __toString() method, that returns username, and it is used across the application, so I can't change it. In the 'create Subscription' form, I have AssociationField::new('user'), where I'm able to find User by his name.

But this is inconvenient, since, when I need to create a Subscription, many users with same names pop up. Instead, I want to be able to search Users by ID, or email.

Is there a way to override default behaviour?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

幽梦紫曦~ 2025-01-18 20:59:14

您的 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 属性定义为标签:

AssociationField::new('user')
    ->setFormTypeOption('choice_label', 'email');

Your AssociationField is made using Symfony EntityType. If you look into the form type used by this field.

//AssociationField.php
public static function new(string $propertyName, $label = null): self
{
    return (new self())
    //...
        ->setFormType(EntityType::class)
    //...

It means that you can use every options from it. See more here.

In your case, it's quite easy modifying your label by either defining another property or a callback.

Then you can use the ->setFormTypeOption() to modify the entity type option.

So if you want to use a callback function to define a custom label:

AssociationField::new('user')
    ->setFormTypeOption('choice_label', function ($user) {
        return $user->getEmail();
    });

Or using php 7.4 arrow function:

AssociationField::new('user')
    ->setFormTypeOption('choice_label', fn($user) => $user->getEmail());

You can also define the email property as label:

AssociationField::new('user')
    ->setFormTypeOption('choice_label', 'email');
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文