使用Symfony3和Select 2添加新实体不起作用

时间:2018-07-03 04:51:40

标签: symfony jquery-select2 symfony-forms jquery-select2-4

我正在尝试使用Select2与Symfony3建立一个评分器复杂表格。我希望能够即时创建新的选择实体,但无法使后端代码正常工作。

在各处阅读问题后,我建立了一个DataTransformer来添加和保留新实体,但未调用它。相反,Symfony调用了ChoiceToValueTransformer(我想它是EntityType表单对象的一部分),然后PostgreSQL抛出异常,因为新实体的名称不是有效的UUID(我的PK的是UUID)。

这是以下形式的代码:

class MagazineType extends AbstractType {
private $magazineCollectionTransformer;

public function __construct(MagazineCollectionTransformer $magazineCollectionTransformer)
{
    $this->magazineCollectionTransformer = $magazineCollectionTransformer;
}

/**
 * {@inheritdoc}
 */
public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add(
                $builder->create('magazineCollection', EntityType::class, [
                    'class' => 'AppBundle:MagazineCollection',
                    'placeholder' => 'Choose a collection',
                    'required' => false,
                    'attr' => [
                        'autofocus' => null,
                        'data-select' => 'true'
                    ],
                    'query_builder' => function(EntityRepository $er) {
                        $qb = $er->createQueryBuilder('c');
                        $qb->addOrderBy('c.title', 'ASC');
                        return $qb;
                    }
                ])
                    ->addModelTransformer($this->magazineCollectionTransformer)
            )
    }
}

这里有MagazineCollectionTransformer

class MagazineCollectionTransformer implements DataTransformerInterface {
  protected $em;
  protected $user;

  public function __construct(EntityManagerInterface $em, TokenStorageInterface $tokenStorage)
  {
    $this->em = $em;
    $this->user = $tokenStorage->getToken()->getUser();
  }

  public function transform($magazineCollection)
  {
    if (null === $magazineCollection) {
        return '';
    }

    return $magazineCollection->getTitle();
  }

  public function reverseTransform($value) {
    if (!$value)
    {
        return;
    }

    $magazineCollection = $this->em->getRepository(Collection::class)->find($value);

    if (null === $magazineCollection) 
    {
        $magazineCollection = new MagazineCollection();
        $magazineCollection->setTitle($value);
        $magazineCollection->setUser($this->user);

        $em->persist($magazineCollection);
        $em->flush();
    }

    return $magazineCollection;
  }
}

我做错了什么?如何使用Select2字段添加不存在的实体?

0 个答案:

没有答案