在ManyToOne / OneToMany协会中持久收集表单

时间:2018-01-18 23:02:09

标签: symfony symfony-3.2

我已经阅读并重新阅读,我无法找到问题的正确答案。这是问题所在。我有2个实体。设备,设备分别。

设备:

/**
 * @ORM\OneToMany(
 *     targetEntity="EquipmentPart",
 *     mappedBy="equipment",
 *     orphanRemoval=true,
 *     cascade={"persist"})
 */

private $parts;

public function __construct()
{
    $this->parts = new ArrayCollection();
} 
... getters and setters...

...
public function getParts()
{
    return $this->parts;
}

public function setParts($parts)
{
    $this->parts = $parts;
}

EquipmentPart:

/**
 * @ORM\ManyToOne(targetEntity="Equipment", inversedBy="parts")
 * @ORM\JoinColumn(nullable=false)
 */
private $equipment;

...getters and setters
...

public function getEquipment()
{
    return $this->equipment;
}

public function setEquipment(Equipment $equipment)
{
    $this->equipment = $equipment;
}

设备表格:

$builder->add("parts", CollectionType::class, [
                "label" => false,
                "entry_type" => EquipmentPartForm::class,
                "allow_delete" => true,
                "allow_add" => true,
                "by_reference" => false

            ]);

equipmentPart表单只有partnumber并且命名为字段。由于FK为空,我不断收到约束错误。

我的控制器非常简单:

public function addEquipment(Request $request)
{
$equipment = new Equipment();
$form = $this->createForm(EquipmentForm::class, $equipment);
    $form->handleRequest($request);

    if($form->isSubmitted() && $form->isValid()){
        $em = $this->getDoctrine()->getManager();
        $em->persist($form->getData());
        $em->flush();
 ...
 ...

我做错了什么?

2 个答案:

答案 0 :(得分:0)

你忘记了什么。将EquipmentPart实体添加到设备实体。

//EquipmentEntity
public function addEquipmentPart(EquipmentPart $equipmentPart)
{
    $this->parts[] = $equipmentPart;
    $equipmentPart->setEquipment($this);
}

在表单中,选项"by_reference" => false会调用此函数,请参阅doc

我希望我帮助你

答案 1 :(得分:0)

经过无数个小时寻找答案后,我终于找到了答案。我得到约束错误或“无法确定属性的访问类型”(删除setParts setter时)的原因是因为symfony无法找到我的加法器和移除方法。

由于某些奇怪的原因,如果没有正确的名称,symfony将无法工作或找到加法器或移除方法。像这样,

* public function addEquipmentPart(...)
* public function addEquipmentParts(...)
* public function addParts(...)

无效

请记住(在这种情况下),无论我的属性$ parts,该方法都是单数。

正确的方法是:

public function addPart(EquipmentPart $equipmentPart){
    $equipmentPart->setEquipment($this);
    $this->parts[] = $equipmentPart;
}

public function removePart(EquipmentPart $equipmentPart){
    $this->parts->removeElement($equipmentPart);
}