How to insert CollectionType unmapped image into db in Symfony?

42 Views Asked by At

How to insert CollectionType unmapped image into db in Symfony?

This is the code

ImageType Form:

->add('image', FileType::class, [
    'mapped' => false,
])

ProjectType Form:

->add('images', CollectionType::class, [
    'entry_type' => ImageType::class,
    'allow_add' => true,
    'allow_delete' => true,
    'prototype' => true,
    'label' => false,
    'by_reference' => false,
])

Controller:

$project->setPdf($pdf);
$images = new Images();
foreach($project->getImages() as $key => $img) {
    $imgName = $imageUpload->uploadImage($form->get('images')[$key]['cropped_file']->getData(), $img);
    $img->setImage($imgName);
    $project->addImage($img);
}
dd($project);

What I want to achieve: I want to Insert Project OneToMany with Images into db

What I tried: When I remove $project->addImage($img); dd($project) One related object Images is displayed but the image is null as it is mapped => false ,

        0 => App\Entity\Images {#1741
            -id: null
            -image: null
            -project: App\Entity\Project {#1108}
        }

but when I add $project->addImage($img); I see 2 Image object one has image => and the other has image as show below.

- images: ArrayCollection {
    -elements: array:2 [
        0 => App\Entity\Images {#1741
            -id: null
            -image: null
            -project: App\Entity\Project {#1108}
        }
        1 => App\Entity\Images {#1858
            -id: null
            -image: "John-Doe-65cbcbb17a4a0.png"
            -project: App\Entity\Project {#1108}
        }
    ]
}

Entity:

#[ORM\OneToMany(mappedBy: 'project', targetEntity: Images::class, cascade : ['persist','remove'])]
private Collection $images;

If I remove image mapped => false then it works fine, but since I had to crop image and upload I had to do mapped=> false. I even tried filtering inside foreach loop but it didn't worked.

0

There are 0 best solutions below