EntityType as an input field?

2019-08-07 05:21发布

问题:

I'm trying to create a form with a CollectionType field containing an email field (which is one of two fields of an entity) which I want to add and remove as I wish.

Here's the scenario:

I have three entities: User, Cluster and the relationship between both called ClusterAdministrator.

Entity User has plenty of all-around attributes (id, name, email, etc). Entity Cluster has a lot of attributes too, and one of them is administrators, which is an ArrayCollection. Entity ClusterAdministrator has 3 attributes: id, user and cluster.

My BD has around 50K users. If I add an CollectionType field of a UserType, and my UserType is a form with user as a normal EntityType, app will crash because it takes more than 30seconds to render such a huge select box. If I my UserType is a form with user as an EmailType, the form is well rendered (see here), but when I click save I get the error:

Expected argument of type "App\AppBundle\Entity\User", "string" given

How do I make this work just by showing the email field?

Sorry guys, I'm quite newbie to Symfony. I'll appreciate all of your precious help.

回答1:

You should use Data Transformer available in Symfony. All that transformer does is, transform the string(User name or email) to relevant User object. Which should solve your problem.

For a better user experience, you can convert the text box to an autocomplete with the help of jQuery. I used it long back. I used PUGXAutoCompleteBundle to generate an autocomplete field and created a custom Transformer to feed the object to parent entity.

I can share some code snippet later by tomorrow if required.

Hope this helps!



标签: forms symfony