如何强制底层表单对象超过父实体的关系?
问题描述:
我有一个主实体和第二个。如何强制底层表单对象超过父实体的关系?
比方说你有一张地图,地图上有坐标点。
我希望能够为点添加动态新记录,所以我选择了表单类型的集合类型。
我也有第二个实体的正确表单类型。一切都可以,除了新增加的点不会与主实体保持一致。我怎么能告诉表格超越父实体并设置适当的设置者?
$builder->add('routePoints', 'collection', ['required' => false,'label' => '','attr'=>['class'=>'route-point'],'by_reference'=> true, 'type' => new MapCoordinateAdminType(), 'allow_add' => true, 'delete_empty' => true, 'allow_delete' => true, 'translation_domain' => 'maps']);
主实体
/**
* @var array
* @ORM\OneToMany(targetEntity="ADN\CustomBundle\Entity\MapCoordinate", cascade={"persist","remove"}, mappedBy="map")
* @ORM\JoinColumn(onDelete="CASCADE",name="route_points",nullable=true, referencedColumnName="map")
*/
protected $routePoints;
点实体
/**
* @ORM\ManyToOne(inversedBy="routePoints", targetEntity="ADN\CustomBundle\Entity\CycleMap")
* @ORM\JoinColumn(name="map",referencedColumnName="id")
*/
protected $map;
答
你的第二个实体实例不会保留,因为它们属于双向关系的反向端。您可以在Doctrine documentation找到更多关于此的信息。
为了解决您的问题,您还需要更新拥有方。要做到这一点,您的主实体需要进行单行更改:
<?php
/** Master entity */
use ADN\CustomBundle\Entity\MapCoordinate;
class CycleMap
{
// ...
public function addRoutePoint(MapCoordinate $routePoint)
{
// The magical line
$routePoint->setMap($this);
$this->routePoints[] = $routePoint;
return $this;
}
}