I'm facing a problem with persisting OneToMany relationship data into the database. Following is the Code:
Item Type
->add('title')
->add('image',FileType::class)
->add('size', CollectionType::class,[
'entry_type'=> SizeType::class,
'entry_options' => ['label' => false],
'by_reference' => false,
'allow_add' =>true,
'allow_delete' => true
])
->add('content',CKEditorType::class)
->add('save', SubmitType::class);
Item Entity
class Item
{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="string", length=255)
*/
private $title;
/**
* @ORM\OneToMany(targetEntity=Size::class, mappedBy="size",cascade={"persist"})
*/
private $size;
public function __construct()
{
$this->size = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
/**
* @return Collection|Size[]
*/
public function getSize(): Collection
{
return $this->size;
}
public function addSize(Size $size): self
{
if (!$this->size->contains($size)) {
$this->size[] = $size;
$size->setSize($this);
}
return $this;
}
public function removeSize(Size $size): self
{
if ($this->size->removeElement($size)) {
// set the owning side to null (unless already changed)
if ($size->getSize() === $this) {
$size->setSize(null);
}
}
return $this;
}
}
Size Entity
class Size
{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\ManyToOne(targetEntity=Item::class, inversedBy="size", fetch="EAGER")
*/
private $size;
public function getSize(): ?Item
{
return $this->size;
}
public function setSize(?Item $size): self
{
$this->size = $size;
return $this;
}
}
Controller
/**
* @Route("/admin/post-product", name="post_product")
*/
public function postProduct(Request $request, SluggerInterface $slugger): Response
{
$item = new Item();
$size = new Size();
$form = $this->createForm(ItemType::class, $item);
$form->handleRequest($request);
if($form->isSubmitted()){
$file_image = $form->get('image')->getData();
dump($item->getSize());
//die;
if($file_image){
//image
}
$sizes = $item->getSize();
$item->addSize($sizes);
$em = $this->getDoctrine()->getManager();
$em->persist($item);
$em->flush();
return $this->redirectToRoute('post_product');
}
return $this->render('admin/post-product.html.twig',[
'form' => $form->createView(),
]);
}
My problem here is I'm not able to save the data into database I have tried with loops ,but I couldn't. The class Item is onetomany with Size. Which is Item has related sizes(s,m,l,xl,xxl). What I want o achieve here is that when I click the save button the item and the size table must be populated. Please help me..