Parsing comma separated string into multiple datab

2019-08-15 20:52发布

I want to create a Symfony 2 Form for a Blog Post. One of the fields that I am wondering how might I implement is the tags field. Post has a many-to-many relationship with Tag. I want my Form to have 1 text box where users enter in a comma separated list of tags. Which will then be converted into multiple Tag's.

How should I implement it? Do I:

  • Have a tagsInput field (named differently from in the Entity where $tags should be an ArrayCollection)
  • On POST, I split the tags and create/get multiple tags. Then validate the tags (eg. MaxLength of 32)

1条回答
啃猪蹄的小仙女
2楼-- · 2019-08-15 21:11

I think you are already on the right way since I saw your other question about the form type. I will just comfort you with your choice.

A form type is probably the best way to go. With the form type, you will be able to display a single text field in your form. You will also be able to transform the data into a string for display to the user and to an ArrayCollection to set it in your model. For this, you use a DataTransformer exactly as you are doing in your other question.

With this technique, you don't need an extra field tagsInput in your model, you can have only a single field named tags that will an ArrayCollection. Having one field is possible because the you form type will transform that data from a string to an ArrayCollection.

For the validation, I think you could use the Choice validator. This validator directive seems to be able to validate that an array does not have less than a number of item and not more than another number. You can check the documentation for it here. You would use it like this:

// src/Acme/BlogBundle/Entity/Author.php
use Symfony\Component\Validator\Constraints as Assert;

class Post
{
    /**
     * @Assert\Choice(min = 1, max = 32)
     */
    protected $tags;
}

If it does not work or not as intended, what you could do is to create a custom validator. This validator will then be put in your model for the tags field. This validator would validate the an array have a maximum number of element no greater than a fixed number (32 in your case).

Hope this helps.

Regards,
Matt

查看更多
登录 后发表回答