在Symfony 2.8中,我有Movie
个实体,其中actors
字段为ArrayCollection
实体Actor
(ManyToMany
),我想要该字段是ajax加载的Select2。
当我不使用Ajax时,表单是:
->add('actors', EntityType::class, array(
'class' => Actor::class,
'label' => "Actors of the work",
'multiple' => true,
'attr' => array(
'class' => "select2-select",
),
))
它有效,这就是在表单提交后显示器显示的内容:http://i.imgur.com/54iXbZy.png
Actors的数量增长了,我想在Select2上使用Ajax自动完成器加载它们。我将表单更改为ChoiceType
:
->add('actors', ChoiceType::class, array(
'multiple' => true,
'attr' => array(
'class' => "select2-ajax",
'data-entity' => "actor",
),
))
//...
$builder->get('actors')
->addModelTransformer(new ActorToNumberModelTransformer($this->manager));
我制作了DataTransformer:
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Persistence\ObjectManager;
use CompanyName\Common\CommonBundle\Entity\Actor;
use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Exception\TransformationFailedException;
class ActorToNumberModelTransformer implements DataTransformerInterface
{
private $manager;
public function __construct(ObjectManager $objectManager)
{
$this->manager = $objectManager;
}
public function transform($actors)
{
if(null === $actors)
return array();
$actorIds = array();
$actorsArray = $actors->toArray();
foreach($actorsArray as $actor)
$actorIds[] = $actor->getId();
return $actorIds;
}
public function reverseTransform($actorIds)
{
if($actorIds === null)
return new ArrayCollection();
$actors = new ArrayCollection();
$actorIdArray = $actorIds->toArray();
foreach($actorIdArray as $actorId)
{
$actor = $this->manager->getRepository('CommonBundle:Actor')->find($actorId);
if(null === $actor)
throw new TransformationFailedException(sprintf('An actor with id "%s" does not exist!', $actorId));
$actors->add($actor);
}
return $actors;
}
}
注册表格:
common.form.type.movie:
class: CompanyName\Common\CommonBundle\Form\Type\MovieType
arguments: ["@doctrine.orm.entity_manager"]
tags:
- { name: form.type }
但似乎永远不会调用reverseTransform()
。我甚至把die()
放在它的开头 - 什么也没发生。这是表单提交后显示的概要文件:http://i.imgur.com/qkjLLot.png
我尝试添加ViewTransformer(代码在这里:pastebin - > 52LizvhF - 我不想粘贴更多,我不能发布超过2个链接),结果相同,但{{1}除外正在被调用并返回它应该返回的内容。
答案 0 :(得分:1)
我知道这是一个老问题,但我遇到了一个非常类似的问题。事实证明,我必须明确地将复合选项设置为false。
也就是说,对于add()方法的第三个参数,您需要添加' compound =>假&#39 ;.