Vichuploader Bundle not working while updating image

64 views Asked by At

I have written code which uploads images successfully ,but when I try to update it doesn't works.

#[Route(path: '/admin/add-project', name: 'add-project')]
public function addProject(Request $request): Response
{
    $project = new Project();
    $form = $this->createForm(ProjectType::class, $project);
    $form->handleRequest($request);
    if($form->isSubmitted() && $form->isValid()) {
        $this->em->persist($project);
        $this->em->flush();

        $this->addFlash('message', 'Project added successfully.');

        return $this->redirectToRoute('list-project');
    }
    return $this->render('admin/add_project.html.twig', [
        'form' => $form,
    ]);
}

#[Route(path: '/admin/update-project/{id}', name: 'update-project')]
public function updateProject(Request $request, $id): Response
{
    $project = $this->em->getRepository(Project::class)->find($id);  
    $form = $this->createForm(ProjectType::class, $project);
    $form->handleRequest($request);
    if($form->isSubmitted() && $form->isValid()) {
        $this->em->persist($project);
        $this->em->flush();

        $this->addFlash('message', 'Project updated successfully.');

        return $this->redirectToRoute('list-project');
    }
    return $this->render('admin/add_project.html.twig', [
        'form' => $form,
    ]);
}

ProjectType

        ->add('imageFile', VichImageType::class, [
            'required' => false,
            'allow_delete' => true,
            'download_label' => '',
            'delete_label' => '  ',
            'asset_helper' => true,
            'download_uri' => false,
            'image_uri' => false,
            'constraints' => $constraints
        ])

Project Entity

use Symfony\Component\HttpFoundation\File\File;
use Vich\UploaderBundle\Mapping\Annotation as Vich;

#[ORM\Entity(repositoryClass: ProjectRepository::class)]
#[Vich\Uploadable]\
class Project
{
#[Vich\UploadableField(mapping: 'projects', fileNameProperty: 'image')]
private ?File $imageFile = null;

When I do dd($project) I can see the new image. Also there is no error. I have similar code for other section it working well but not here in Project. As seen in above code the add-project and update-project code are same, but my concerns is add-project works well but not update-project.

1

There are 1 answers

1
David Rojo On

The annotation #[Vich\Uploadable] should be placed in the class, not in the property.

#[Vich\Uploadable]
class MyClass {

  #[ORM\Entity(repositoryClass: ProjectRepository::class)]
  #[Vich\UploadableField(mapping: 'projects', fileNameProperty: 'image')]
  private ?File $imageFile = null;

}