I have a problem saving entities with forms. The relationship that gives me problems is many-to-many bidirectional.
Agent Entity
/**
* @var \Doctrine\Common\Collections\ArrayCollection $agentLists
*
* @ORM\ManyToMany(targetEntity="AgentList", inversedBy="agents")
* @ORM\JoinTable(name="agent_agentlist",
* joinColumns={@ORM\JoinColumn(name="agent_id", referencedColumnName="id")},
* inverseJoinColumns={@ORM\JoinColumn(name="agentlist_id", referencedColumnName="id")}
* )
*/
protected $agentLists;
/**
* Get agent lists
*
* @return \Doctrine\Common\Collections\ArrayCollection
*/
public function getAgentLists()
{
return $this->agentLists;
}
/**
* Add agent list to agent
*
* @param AgentList $agentList
*/
public function addAgentList(AgentList $agentList)
{
$this->agentLists->add($agentList);
$agentList->addAgent($this);
}
/**
* Remove agent list from agent
*
* @param AgentList $agentList
*/
public function removeAgentList(AgentList $agentList)
{
$this->agentLists->removeElement($agentList);
$agentList->removeAgent($this);
}
AgentList Entity
/**
* @var \Doctrine\Common\Collections\ArrayCollection $agents
*
* @ORM\ManyToMany(targetEntity="Agent", mappedBy="agentLists")
*/
protected $agents;
/**
* Get agents
*
* @return \Doctrine\Common\Collections\ArrayCollection
*/
public function getAgents()
{
return $this->agents;
}
/**
* Add agent
*
* @param Agent $agent
*/
public function addAgent(Agent $agent)
{
$this->agents[] = $agent;
}
/**
* Remove agent
*
* @param Agent $agent
*/
public function removeAgent(Agent $agent)
{
$this->agents->removeElement($agent);
}
In Agent Type
->add('agentLists', null, array('choices' => $this->commercial->getAgentLists(), 'required' => false));
In AgentList Type
->add('agents', null, array(
'required' => false,
'choices' => $commercial->getAgents()
It only works if I use AgentType. If I use AgentListType don't save Agents Relations! In the same way, If I:
$agent->addAgentList($agentList);
All works fine! If I:
$agentList->addAgent($agent);
don't save nothing...
is not enough. Since it's bidirectional you have to add/set both agent to list and list to agent.
This could work:
Remember you have to first persist one entity before you can persist and flush the other related entity.