Symfony 4.1:动态的ManyToMany EntityType

时间:2018-11-28 11:36:45

标签: symfony-forms symfony4

我有一个具有ManyToMany字段的实体,使用EntityType和仅限于现有链接的选择进行呈现:

实体示例:

/**
 * @var House[]|ArrayCollection
 *
 * @ORM\ManyToMany(targetEntity=House::class, fetch="LAZY")
 * @ORM\JoinTable(name="city_house")
 */
private $houses;

/**
 * constructor.
 */
public function __construct()
{
    $this->houses = new ArrayCollection();
}


public function addHouse(House $house)
{
    if ($this->houses->contains($house)) {
        return $this;
    }

    $this->houses[] = $house;

    return $this;
}

public function removeHouse(House $house): bool
{
    if (!$this->houses->contains($house)) {
        return true;
    }

    return $this->houses->removeElement($house);
}

/**
 * Get brands.
 *
 * @return \Doctrine\Common\Collections\Collection
 */
public function getBrands(): ?Collection
{
    return $this->brands;
}

还有我的formBuilder:

    $builder
        ->add('houseTypes', EntityType::class, [
            'multiple' => false,
            'required' => false,
            'mapped' => false,
            'class' => HouseType::class,
        ])
        ->add('houses', EntityType::class, [
            'multiple' => true,
            'required' => false,
            'class' => House::class,
            'by_reference' => false,
            'choices' => $builder->getData()->getHouses(),
        ])

我使用multiselect js来在房屋EntityType中添加过滤的房屋(按类型)。

JS部分运行良好,它添加了选择链接的选项

        <option value="6">House (type)</option>

当我从该列表中删除元素时,symfony会很好地删除链接。 但是,当添加新元素时,formValdator会引发错误。

ConstraintViolation {#3985 ▼
  root: Form {#2783 …}
  path: "children[houses]"
  value: [▼
    "57"
    "3"
    "2"
  ]
}

TransformationFailedException {#2663 ▼
  #message: "Unable to reverse value for property path "houses": Could not find all matching choices for the given values"
  #code: 0
  #file: "/srv/vendor/symfony/form/Form.php"
  #line: 1115
  trace: {▶}
   …1
}

TransformationFailedException {#2678 ▼
  #message: "Could not find all matching choices for the given values"
  #code: 0
  #file: "/srv/vendor/symfony/form/Extension/Core/DataTransformer/ChoicesToValuesTransformer.php"
  #line: 68
  trace: {▶}
}

您是否知道如何解决该问题?

1 个答案:

答案 0 :(得分:0)

我想出了办法,我们需要使用表单事件。

因此,我添加了侦听器:

$builder->addEventListener(FormEvents::PRE_SET_DATA, [$this, 'onPreSetData']);
$builder->addEventListener(FormEvents::PRE_SUBMIT, [$this, 'onPreSubmit']);

添加回调函数

/**
 * @param FormEvent $event
 */
public function onPreSubmit(FormEvent $event)
{
    $form = $event->getForm();
    $data = $event->getData();
    $brandsCollection = null;
    if (isset($data['houses'])) {
        $housesCollection = $this->em->getRepository(House::class)->findById($data['houses']);
    }

    $houses = new ArrayCollection($housesCollection ?? []);

    $this->addHouse($form, $houses);
}

/**
 * @param FormEvent $event
 */
public function onPreSetData(FormEvent $event)
{
    $promo = $event->getData();
    $form = $event->getForm();

    $houses = $promo->getHouses() ? $promo->getHouses() : null;

    $this->addHouse($form, $houses);
}

/**
 * @param FormInterface   $form
 * @param Collection|null $houses
 */
protected function addHouse(FormInterface $form, Collection $houses = null)
{
    $form->add('houses', EntityType::class, [
        'multiple' => true,
        'required' => false,
        'class' => House::class,
        'by_reference' => false,
        'choices' => $houses,
    ]);
}