[首先,对不起我的英语不好。我需要创建表单来为Article添加新标签,但是当我提交表单时,请求数据不会在我的表单中处理,因为新添加的标签不在实体数组集合中。可以向具有多对一关联的表单字段添加自定义选择吗?
这是我的代码:
public function buildForm(FormBuilderInterface $builder, array $options)
{
dump($builder->getFormConfig()); die;
/** @var Domain $domain */
$domain = $this->currentDomainService->getCurrentDomain();
$builder
->add('articleTitle', TextType::class, [])
->addEventSubscriber(new TagsChoicesSubscriber())
;
}
class TagshoicesSubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents()
{
return array(
FormEvents::PRE_SET_DATA => ['preSetData', -50],
FormEvents::PRE_SUBMIT => ['preSetData', -50],
);
}
public function preSetData(FormEvent $event, $childName)
{
$choices = array();
/** @var Article $article */
$article = $event->getData();
if ($article instanceof Article) {
foreach ($article->getTags() as $tag) {
$tags[] = $tag->getTagName();
}
$event->getForm()->add(
'tags',
ChoiceType::class,
[
'multiple' => true,
'mapped' => false,
'choices' => $choices,
'data' => $tags,
'required' => true,
'constraints' => [
new NotBlank(),
],
]
);
}
}
}
/**
* Article
* @ORM\Entity()
*/
class Article
{
/**
* @ORM\OneToMany(targetEntity="App\Entity\Tags", mappedBy="article")
*/
private $tags;
}
/**
* Tag
*
* @ORM\Entity()
*/
class Tag
{
/**
* @ORM\ManyToOne(targetEntity="App\Entity\Article", inversedBy="tags")
* @ORM\JoinColumn(name="article_id", referencedColumnName="id")
*/
private $article;
}
$form = $this->createForm('App\Form\ArticleType', $article);
$form->handleRequest($request);
您需要实现的是集合类型字段,或将多个设置为true的选择类型,这里是Symfony collection type,这里是Symfony choice type,在Tag类中还需要toString函数。让我知道是否有帮助,以防万一您仍然遇到麻烦,我将为您提供一些代码示例