0
votes

I have inherited an application that seems to have existed before the form builder existed. The developer kind of rolled his own with twig macros. Now I want to add a file upload to some existing forms, but I get what seems to be a well known error:

There was 1 error:

myBundle\Tests\Controller\snip\DefaultControllerUnitTest::testCanStoreDocumentAtS3 Exception: Serialization of 'Symfony\Component\HttpFoundation\File\UploadedFile' is not allowed

C:\apath\vendor\symfony\symfony\src\Symfony\Component\HttpKernel\DataCollector\DataCollector.php:27

C:\apath\vendor\symfony\symfony\src\Symfony\Component\HttpKernel\Profiler\Profiler.php:218

The solutions is to unmap the file field:

$builder->add('pic','file'); to this :

$builder->add('pic','file', array('mapped'=>false));

But in this case a builder is not used. Instead it looks like this:

{# file(name, value) #}
{% macro file(name, value) %}
   <input type="file" name="{{ name }}" id="{{ name }}" value="{{ value }}" />
{% endmacro %}

Is there anything I can add to this macro, or do in the controller action to keep the Profiler from serializing this?

1

1 Answers

1
votes

The answer was in part pilot error, but there is enough going on here that I hope I can help others avoid the same pitfall.

This error was triggered by a unit test where I was simulating a file upload along with other parameters. Initially the code that caused this error was:

$photo = new UploadedFile(
    __DIR__ . '/TestReportMethod.xlsx',
    'TestReportMethod.xlsx',
    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    123
);
....
$form['reportFile'] = $photo;
//submit 

This caused the error in my original post.

After trying a few things I moved to this form instead.

$crawler = $this->client->request('POST', 
  $url, 
  array('id' => 328),
  array('agencyInfoId' => 328),
  array('reportFile' => $photo)
);

Which causes an InvalidArgumentException I think a little better example in the cookbook could have prevented. The correct form needs to be an array of parameter values, followed by an array of files:

$crawler = $this->client->request('POST', 
  $url, 
  array('id' => 328,
        'agencyInfoId' => 328),
  array('reportFile' => $photo)
);

I hope this helps somebody else!