Bonjour à tous,

Voilà, dans mon projet Symfony, je cherche à modifier l'image d'une tente sur ma route edit.
Pour info, la tente à son entité (Tent) et les images ont leur entité aussi (Image).

Merci pour votre aide.

TentController.php

#[Route('/edit/{tent}', name: 'edit', methods: ['GET', 'POST'])]
    public function edit(Request $request, Tent $tent, TentRepository $tentRepository): Response
    {
        $form = $this->createForm(TentType::class, $tent);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $existingImages = $tent->getImage();
            dump('existingImages', $existingImages);

            foreach ($existingImages as $existingImage) {
                dump('existingImage', $existingImage);

                if ($form->has('imageFile')) {
                    $imageFile = $form->get('imageFile')->getData();
                    dump('imageFile', $imageFile);

                    $existingImage->setImageFile($imageFile);
                }
            }

            $tentRepository->save($tent, true);
            $this->addFlash('success', 'La categorie {$tent->getName()} a bien été modifiée');

            return $this->redirectToRoute('admin_tent_index', [], Response::HTTP_SEE_OTHER);
        }

        return $this->renderForm('admin/tent/edit.html.twig', [
            'tent' => $tent,
            'form' => $form,
        ]);
    }

Le raport des dumps

In TentController.php line 80:
"existingImages"
In TentController.php line 80:
Doctrine\ORM\PersistentCollection {#909 ▼
  #collection: Doctrine\Common\Collections\ArrayCollection {#904 ▶}
  #initialized: false
  -snapshot: []
  -owner: App\Entity\Tent {#859 ▶}
  -association: array:15 [ …15]
  -em: Doctrine\ORM\EntityManager {#630 …11}
  -backRefFieldName: "tent"
  -typeClass: Doctrine\ORM\Mapping\ClassMetadata {#883 …}
  -isDirty: false
}

In TentController.php line 82:
"existingImage"
In TentController.php line 82:
App\Entity\Image {#1792 ▼
  -id: 202
  -imageFile: null
  -imageName: "people-ge90716ecd-640-64959cf40040c645006712.jpg"
  -original: "people-ge90716ecd_640.jpg"
  -addedAt: DateTimeImmutable @1687526643 {#1787 ▶}
  -updatedAt: DateTimeImmutable @1687526644 {#1462 ▶}
  -isActive: 1
  -tent: App\Entity\Tent {#859 ▶}
  -product: null
  -subcategory: null
}

In TentController.php line 85:
"imageFile"
In TentController.php line 85:
Symfony\Component\HttpFoundation\File\UploadedFile {#18 ▼
  -test: false
  -originalName: "people-ge90716ecd_640.jpg"
  -mimeType: "image/jpeg"
  -error: 0
  path: "/tmp"
  filename: "phpj6CPC6"
  basename: "phpj6CPC6"
  pathname: "/tmp/phpj6CPC6"
  extension: ""
  realPath: "/tmp/phpj6CPC6"
  aTime: 2023-06-23 16:19:40
  mTime: 2023-06-23 16:19:40
  cTime: 2023-06-23 16:19:40
  inode: 14286891
  size: 96349
  perms: 0100600
  owner: 1000
  group: 1000
  type: "file"
  writable: true
  readable: true
  executable: false
  file: true
  dir: false
  link: false
}

TentType.php (je ne met pas tout)

->add('imageFile', VichImageType::class, [
                'mapped' => false,
                'help' => 'Formats acceptés : jpg, png. Taille maximale : 5Mo',
                'required' => false,
                'allow_delete' => false,
                'download_uri' => false,
                'image_uri' => false,
                'asset_helper' => false,
                'constraints' => [
                    new Image([
                        'maxSize' => '5M',
                        'mimeTypes' => [
                            'image/jpeg', 'image/png', 'image/jpg'
                        ],
                        'mimeTypesMessage' => 'Veuillez télécharger un document image valide (jpg, jpeg, png)',
                    ])
                ],
            ]);

Entité Image.php, config VichUploader

#[Vich\UploadableField(mapping: 'img', fileNameProperty: 'imageName', originalName: 'original')]
    private ?File $imageFile = null;

    #[ORM\Column(length: 255)]
    #[Groups(['image:read', 'tent:read', 'product:read', 'subcategory:read'])]
    private ?string $imageName = null;

    // Sert à créer mon URL pour l'export en json pour API
    #[ORM\Column(length: 255)]
    #[Groups(['image:read', 'tent:read', 'product:read', 'subcategory:read'])]
    private ?string $original = null;

    public function setImageFile(?File $imageFile = null): void
    {
        $this->imageFile = $imageFile;

        if (null !== $imageFile) {
            $this->updatedAt = new \DateTimeImmutable();
        }
    }

    public function getImageFile(): ?File
    {
        return $this->imageFile;
    }

    public function getImageName(): ?string
    {
        return $this->imageName;
    }

    public function setImageName(string $imageName): self
    {
        $this->imageName = $imageName;

        return $this;
    }

    // TODO: Fix this
    public function getOriginal(): ?string
    {
        $this->original = $this->imageName;
        $path = "http://localhost:8000/uploads/img/";
        return $path . $this->original;
    }
    // public function getOriginal(): ?string
    // {
    //     return $this->original;
    // }

    public function setOriginal(string $original): self
    {
        $this->original = $original;

        return $this;
    }

Config vich_uploader.yaml

vich_uploader:
    db_driver: orm

    metadata:
        type: attribute

    mappings:
        img:
            uri_prefix: uploads/img
            upload_destination: '%kernel.project_dir%/public/uploads/img'
            namer: Vich\UploaderBundle\Naming\SmartUniqueNamer
            inject_on_load: false
            delete_on_remove: true
            delete_on_update: true

Ce que je veux

Pouvoir modifier mon Image.

Ce que j'obtiens

Expected argument of type "string", "null" given at property path "imageName".

2 réponses


Grafikart
Réponse acceptée

Tu devrais accepter null dans le setter de imageName car quand l'entité est vide la valeur est null. setImageName(?string $imageName)

Impécable ! Merci :D