Reputation: 168
i have a Agency Entity with a fields $owns
looks like
/**
* @ORM\ManyToMany(targetEntity="AppBundle\Entity\ShipType", inversedBy="owners")
*/
protected $owns;
on ShipType Entity i have
/**
* @ORM\ManyToMany(targetEntity="AppBundle\Entity\Agency", mappedBy="owns")
*/
private $owners;
doctrine created a relations table for association between tables with agency_id and ship_type_id
i'm trying to get a form to work for assign each agency to a ship type ( owns ) im trying to achieve logging as an agency
so far i got
public function gShips(Request $request): Response {
$u = $this->getUser();
$ag = new Agency();
$form = $this->createForm(ChooseShipsType::class, $ag);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()->getManager();
$a = $form->getData();
$em->persist($a);
$em->flush();
}
return $this->render('agency/sships.html.twig', [
'adForm' => $form->createView()
]);
}
and the form
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('ships', EntityType::class, [
'class' => 'AppBundle:ShipType',
'expanded' => true,
'multiple' => true,
])
->add('save', SubmitType::class)
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => 'AppBundle\Entity\Agency'
]);
}
the form is showing, but can't get it to persist because it's trying to create a new Agency, i can't figure out how to use the relation table between these two tables
thank you in advance
Upvotes: 0
Views: 46
Reputation: 1828
Check the constructor of your Agency class. Make sure it has the following:
$this->owns = new ArrayCollection();
And then, make sure you have an addOwns()
method:
public function addOwns(ShipType $shipType)
{
$this->owns[] = $shipType;
}
And also a setter:
public function setOwns($owns)
{
if ($owns instanceof ArrayCollection) {
$this->owns = $owns;
} else {
if (!$this->owns->contains($owns)) {
$this->owns[] = $owns;
}
$this->owns;
}
return $this;
}
Also, make sure you have the getter with the default content. That should do.
PS: You shouldn't name your properties as verbs though, but that's another thing.
Upvotes: 1