【发布时间】:2016-02-24 18:39:47
【问题描述】:
在 Symfony 2.8 中,我有 Movie 实体和 actors 字段,它是实体 Actor (ManyToMany) 的 ArrayCollection,我希望该字段是 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
演员的数量增长了,我想在 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 个链接),结果相同,除了 reverseTransform() 正在调用并返回它应该返回的内容。
【问题讨论】: