有与Manuttomany关系的服务和标签实体。
class Service {
/**
* @ORMManyToMany(targetEntity="Tag", mappedBy="serviceList",cascade={"persist"})
*/
private $tagList;
}
class Tag{
/**
* @var string
*/
private $name;
/**
* @ORMManyToMany(targetEntity="Service", inversedBy="tagList")
* @ORMJoinTable(name="tags_services")
*/
private $serviceList;
}
这是ServiceType
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('title', TextType::class, array(
'label' => 'Title',
))
->add('tags', TextType::class, array(
'label' => 'Tags',
'mapped' => false
))
;
}
编辑服务实体时,如何获得标签中逗号分隔的服务标签字段?
例如,我使用标记列表的"数学导师"服务:"数学","导师","课程"。当我尝试编辑它时,表格应该看起来像:
| title | Math tutor | <- text field
| tags | Math, Tutor, Lessons | <- text field
您应该使用datatransformer:http://symfony.com/doc/current/form/data_transformers.html
这是一个简单情况的一个小例子:
$builder->add('tags', TextType::class);
$builder->get('tags')
->addModelTransformer(new CallbackTransformer(
function ($tagsAsArray) {
// transform the array to a string
return implode(', ', $tagsAsArray);
},
function ($tagsAsString) {
// transform the string back to an array
return explode(', ', $tagsAsString);
}
))
;