I'm using VichUploaderBundle in Symfony 4 and I have a question about using a form to send in a bunch of photos. To do this I have to use CollectionType and a one-to-many relationship (One product has several photos). Below I present the code which only shows me an empty frame of the form, and it lacks buttons for adding photos as they are in this uploader. I do not understand why this is happening.
Product entity (one-to-many):
/**
* @var ProductMultiImage[]
* One Product has Many Images.
* @ORM\OneToMany(targetEntity="App\Entity\Image\ProductMultiImage", mappedBy="product", cascade={"persist"})
* @ORM\JoinColumn(nullable=true)
*/
private $productMultiImages = null;
Image entity (many-to-one):
/**
* Many Images have One Product.
* @ORM\ManyToOne(targetEntity="App\Entity\Admin\Product", inversedBy="productMultiImages", cascade={"persist"})
* @ORM\JoinColumn(name="product_id", referencedColumnName="id", nullable=true)
*/
private $product = null;
Form for adding photos:
class ProductImageType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('productMultiImages', CollectionType::class, array(
'data_class' => ImageType::class,
'allow_add' => true,
'allow_delete' => true,
'by_reference' => false,
))
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => null,
]);
}
}
ImageType:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('imageFile', VichImageType::class)
;
}
Where i can find any solution ?
If $productMultiImages is null then the form won't have anything to populate with. Set it to an empty array collection and add at least one empty Image entity to it.
In the Product entity's __constuct()
Or add those to an instantiated Product before passing it into the form builder.
Last time I used it VichUploader didn't support multifile upload with a single form file element though. You'll need to use javascript on the client to add an additional file upload element to the form for each image you want to upload. See https://symfony.com/doc/current/form/form_collections.html for more on that.