0
votes

I have a problem with upload files from form. What am i doing wrong ?

Error is: Expected argument of type "App\Entity\Image", "instance of Symfony\Component\HttpFoundation\File\UploadedFile" given at property path "files".

Form->handleRequest(object(Request)) in C:\xampp\htdocs\biuro\src\Controller\OfferController.php (line 29)

My code:

class OfferType:

class OfferType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('name', TextType::class)
            ->add('description', TextareaType::class)
            ->add('files',FileType::class, [
                'multiple' => true
                ]
            )

class OfferController:

 class OfferController extends AbstractController
{
   public function createOffer(Request $request) {
 
        $offer = new Offer();
        $form = $this->createForm(OfferType::class, $offer);
        $form->handleRequest($request);

class entity Offer:

class Offer
{
    /**
     * @ORM\OneToMany(targetEntity="Image", mappedBy="offer", cascade={"persist"})
     */
    private $files;

Template:

<table>
    <tbody>
    <tr>
        <th>Nazwa:</th>
        <td>{{ form_widget(form.name) }}</td>
    </tr>
    <tr>
        <th>Opis:</th>
        <td>{{ form_widget(form.description) }}</td>
    </tr>
    <tr>
        <th>Zdjęcia:</th>
        <td>{{ form_widget(form.files) }}</td>
    </tr>
    <tr>
        <th></th>
        <td>{{ form_widget(form.save) }}</td>
    </tr>
    </tbody>
</table>
2

2 Answers

1
votes

This is because the files provided by the files field in your form are of type UploadedFile, while the entity property mapped to this field, Offer::$files, expects objects of type Image (which is incompatible with UploadedFile, resulting the error you experience). Without help, Symfony can't know how to transform the received UploadedFile objects into the expected Image objects. You will have to tell Symfony how to do this yourself.

Luckily, the Symfony Form component provides a relatively easy way to do this in the form of Data Transformers. Here's an example of how to implement such a transformer for your use case.

1
votes

I recommend the bundle VichUploader

composer require vich/uploader-bundle
# config/services.yaml
parameters:
    app.path.product_images: /uploads/images/products
    # ...

# config/packages/vich_uploader.yaml
vich_uploader:
    # ...
    mappings:
        product_images:
            uri_prefix:         '%app.path.product_images%'
            upload_destination: '%kernel.project_dir%/public%app.path.product_images%'
``