A
A
Andrey Shakhtarin2016-11-04 07:11:27
symfony
Andrey Shakhtarin, 2016-11-04 07:11:27

Array Collection: Why are Array Collection form fields lost after form redirect?

Good day to all! Faced the following problem. There is a form in which everything is displayed as expected and works smoothly. But there is one thing! After the form is submitted, the following happens: Neither the property "0" nor one of the methods "0()", "get0()"/"is0()" or "__call()" exist and have public access in class " Symfony\Component\Form\FormView". It is clear that this field is not located,
then why was everything previously displayed without errors?
The reason for adding the following code: $product->getImage()->add($img); which adds an entity to the collection. But after the redirect, Massim with the collections was simply not added? What could be the reason? Perhaps you need to add an entity from another
entity to the collection?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis, 2016-11-04
@prototype_denis

The Product entity must have addImage, removeImage, getImages methods.
The first two take Image as arguments, the third must return an ArrayCollection consisting of Image.

<?php

class Product 
{
    private $images;
    public function __construct() {
        $this->images = new \Doctrine\Common\Collections\ArrayCollection();
    }
    public function addImage(Image $image) {
        $this->images[] = $image
    }
    public function removeImage(Image $image) {
        $this->images->removeElement($image);
    }
    public function getImages() {
        return $this->images;
    }
}

class Image 
{
    private $image;
    public function getProduct() {
        return $this->product;
    }
    public function setProduct(Product $product) {
        $this->product = $product;
    }
}


// ProductType
$builder->add('images');

// Controller
$entity = new Product(); // $this->getDoctrine()->getRepository(Product::class)->find($id);
$form = $this->createForm(ProductType::class, $entity);
$form->handleRequest($request);
if ($form->isValid()) {
    $images = $entity->getImages();
    // $images === ArrayCollection<Image>
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question