我想做一个这样的技巧:将标签名称作为数组提交,然后将它们转换为实体。提交的数据:
{"title":"Title","description":"Desc", "tags": ["first", "second"]}
形式:
class ImageType extends AbstractType
{
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('title')
->add('description')
->add('imageFile')
->add('tags', CollectionType::class, [
'entry_type' => ImageTagType::class,
'allow_add' => true,
'allow_delete' => true,
'by_reference' => false,
]);
}
/**
* {@inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Image::class,
'csrf_protection' => false,
]);
}
/**
* {@inheritdoc}
*/
public function getBlockPrefix()
{
return 'appbundle_image';
}
}
图片代码表单:
class ImageTagType extends AbstractType
{
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('name');
}
/**
* {@inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\ImageTag'
));
}
/**
* {@inheritdoc}
*/
public function getBlockPrefix()
{
return 'appbundle_imagetag';
}
}
实体与多对多连接。一个图像可以有许多标签,一个标签可以有许多图像。我正在构建API并希望简化标签提交。我该怎么办?
答案 0 :(得分:1)
使用DataTransformer。例如:
....
$builder->get('YOUR_FILED')
->addModelTransformer(new CallbackTransformer(
function ($array) {
// your implementation here
},
function ($array) {
if (!$array) {
return;
}
return new ArrayCollection(array_map(function ($data) {
return $this->someRepository->findOneBy(['FIELD' => $data]);
}, $array));
}
));
....