Symfony 3 FileUpload

I am trying to implement the file upload function for my application using Symfony 3. I have an entiry product that is related to File entiry. Product Part:

 /**
 * @ORM\OneToMany(targetEntity="AppBundle\Entity\File", mappedBy="product")
 * @ORM\OrderBy({"weight" = "DESC"})
 */
protected $files;

and a field in the form:

     ->add('files', FileType::class, array('multiple'=> true, 'data_class'=> 'AppBundle\Entity\File'));

public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults(array(
        'data_class' => 'AppBundle\Entity\Product',
    ));
}

As you can see, I set data_class.

and in the controller I try to process the form

public function addAction(Request $request)
{
    $em = $this->getDoctrine()->getManager();
    $product = new Product();
    $product->setAddedBy($this->getUser());
    $form = $this->createForm(ProductType::class, null);
    $form->handleRequest($request); 
    ...

and I have an error:

The expected argument of type "AppBundle \ Entity \ File", "Symfony \ Component \ HttpFoundation \ File \ UploadedFile", specified

If I discard the data_class mapping, I have no error and no object, just an array. How can I solve this error, how to convert the UploadedFile to a file (Entiry). I am trying to create a Transformer, but I just got a ProductEntiry class, and as a result, it cannot be processed, because it is without files.

+4
1

, . :

$form = $this->createForm(ProductType::class, null);

$product, , . :

$form = $this->createForm(ProductType::class, $product);

, , , , Product :

public function addFile(AppBundle\Entity\File $file) { ... }

, , Product , Symfony UploadedFile. , .

( ) .

"mapped" => false . , ( Product).

, , AppBundle/Entity/File $product setter.

, , . .

UploadedFile File Data Transformer. , . , , Data Transformers Symfony.

, , . Symfony Form, Data Transformers, . . , .

P.S. "", "entiry". "entiry", FYI.

+7

Source: https://habr.com/ru/post/1651707/


All Articles