Reputation: 851
I am attempting to upload a file via an API endpoint controller I have created:
/**
* @Route("/upload", methods="POST")
*/
public function upload(Request $request)
{
$form = $this->createForm(UserFileType::class);
$form->handleRequest($request);
if (!$form->isSubmitted()) {
dd($request->files->get('file'));
}
...
The dd($request->files->get('file'))
is showing my file as expected so I am unclear why isSubmitted()
is returning false when the method is receiving multipart/form-data
POST
request with data. I am submitting the POST
request via Postman
. Why is the form not submitted?
UserFileType:
class UserFileType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('file', FileType::class, [
'mapped' => false,
'required' => true,
'constraints' => [
new File([
'maxSize' => '2M',
'mimeTypes' => [
'application/pdf',
'application/x-pdf',
],
'maxSizeMessage' => 'The file size must not exceed {{ limit }} {{ suffix }}.',
'mimeTypesMessage' => 'The file type {{ type }} is not valid',
])
],
]);
}
Upvotes: 3
Views: 2260
Reputation: 1256
Since this is the first SO thread that comes up for the keywords handlerequest issubmitted false
, I thought I would share what worked for my team on an adjacent issue.
We were getting a false
response when doing a PATCH
request. We eventually realized that we were neglecting to pass Request::METHOD_PATCH
in the method
option when creatin the form. Putting in a ternary statement that set that value was enough to solve our problem.
I hope this helps someone.
Upvotes: 0
Reputation: 38932
For form classes derived from AbstractType
, the form is named using fqcnToBlockPrefix
when it's built through FormFactory
.
You can confirm this by dumping $form->getName()
.
Now, $form->handleRequest
method as implemented performs a number of checks through the request handler before submitting the form.
Your form is not submitting through the request handler handleRequest
method because fields in the request are not properly mapped together with your form name.
You have to map the form name in your HTTP POST request in following way:
[ "user_file" => [ "file" => <uploaded file> ] ]
This may prove to not be straight forward in Postman.
Therefore I recommend to implement your form as a nameless form instead by overriding getBlockPrefix
to return an empty string.
class UserFileType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
//...
}
public function getBlockPrefix()
{
return '';
}
}
Upvotes: 4