Context:
Let there be two entities (correctly mapped for Doctrine).
Post
with properties {$id
(integer, autoinc),$name
(string),$tags
(collection ofTag
)}Tag
with properties {$id
(integer, autoinc),$name
(string),$posts
(collection ofPost
)}
Relationship between these two is Many-To-Many
.
Problem:
When creating a new Post
, I want to immediately add tags to it.
If I wanted to add Tags
that already are peristed, I would create entity field type, no problem with that.
But what would I do, if I wanted to add completely new Tags
too? (Check some of already existing tags, fill name for new tag, maybe add some another new tag, then after submit assign everyting properly to Post
entity)
Create new Post: Name: [__________] Add tags | |[x] alpha |[ ] beta |[x] gamma | |My tag doesnt exist, create new: | |Name: [__________] | |+Add another new tag
Is there any way to do this? I know the basics of Symfony 2, but have no idea how to deal with this. Also surprised me I havent found my answer anywhere, seems like a common problem to me. What am I missing?
My Tag entity has a unique field for the tag name. For add Tags I use a new form type and a transformer.
The Form Type:
The Transformer:
The config.yml
use the new Type:
Similarities, like "symfony" and "smfony" can be prevented with an autocomplete function:
TagController:
form.html.twig:
I took a slightly different approach using Select2's tag input:
It has the advantage that it prevents duplicates on the client side and looks pretty.
To create the newly added entities, I am using a EventSubscriber rather than a DataTransformer.
For a few more details, see my gist. Below are the TagType and the AddEntityChoiceSubscriber.
AppBundle/Form/Type/TagType:
AppBundle/Form/EventListener/AddEntityChoiceSubscriber: