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?
CodePudding user response:
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');