简体   繁体   中英

How to use existing entity in a Symfony2 form?

I've this two entities:

class Article
{
    /** @var ArrayCollection
    protected $tags;
}

class Tag
{
    protected $id;
    protected $name;
}

Basically I've read http://symfony.com/doc/master/cookbook/form/form_collections.html but it does not explain my case.

Let me explain.

I've existing tags in database, so I want to be able to associate multiple Tags to my Article, I don't want to allow the creation of inexistent tags.

Since I'm aiming to use my form in both a REST api and with a web form, I'd like my client be able to use the id only to reference the tags (which would have been fetched before).

Any ideas?

You could use the entity field typ e. It is in practice a choice field type that you can render as a select with multiple selection or as a list of checkboxes . However, if you have many tags there will be too many options and the users will not be happy.

So, I suggest to implement a Stackoverflow-like tagging system.

I did it in a project by using a Javascript tokeninput library, like this by loopj . In practice:

  1. You should first render a text field named tags .

  2. Then you should handle the tag insertion to that input field with the Javascript library for token handling.

  3. The Controller will receive a tokenized string that you have to handle in order to retrieve the Tag entities from Doctrine.

  4. Finally, retrieved a list of Tag entities, assign them to your Article entity and flush everything.

You can use somethig like this:

$builder->add('tags', 'entity', array(
    'class' => 'AcmeHelloBundle:tag',
    'expanded' => true,
    'multiple' => true,
));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM