Symfony file field empty on edit

Viewed 3054

I am reading for a while about this but found nothing that works for me. This is entity

/**
 * @ORM\Column(type="string")
 *
 * @Assert\NotBlank(message="Molimo unesite PDF ili Word fajl.")
 * @Assert\File(mimeTypes={ "application/vnd.openxmlformats-officedocument.presentationml.presentation", "application/vnd.ms-powerpoint", "application/pdf", "application/msword", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"})
 */
private $body;

This is form

// Problem with empty field on edit persist! Form expect FileType but db sends string!!!
            ->add('body', FileType::class,  [
                //'data_class' => null,// <-- If I change it nothing happened.
                'label' => 'Word ili pdf dokument',
                'invalid_message' =>'Id posta nije validan',
                'attr' => [
                    'class' => 'form-group',
        ]])

Everything is very simple and made following docs. I have entity that contains few properties one of them for files ($body). Files are set to be saved in web/uploads/post/ . When I go to edit page I get this error:

"The form's view data is expected to be an instance of class Symfony\Component\HttpFoundation\File\File, but is a(n) string. You can avoid this by setting the "data_class" option to null or by adding a view transformer that transforms a string to an instance of Symfony\Component\HttpFoundation\File\File".

If i set data_status => null field is empty.

What I need is some link to example with this working, Data Transformer maybe?

4 Answers

I was having the same problem in my edit action and solved it by submitting the form manually with the clearMissing parameter set to false instead of using $form->handleRequest($request);, as explained on https://symfony.com/doc/current/form/direct_submit.html:

if ($request->isMethod('POST'))
{
    $form->submit($request->request->get($form->getName()),false);

    if ($form->isSubmitted() && $form->isValid())
    {

This way, the original value of file will not be set to null in case you aren't submitting a new file.

In my case what helped was:

if ($request->isMethod('POST')) {
        $form->submit($request->request->get($form->getName()));
        if ($form->isValid()) {...

to

$form->handleRequest($request);
if ($form->isSubmitted()) {
     if ($form->isValid()) { ...
Related