Reputation: 11303
I have a Symfony FormType including some onPostSubmit actions in an Event Listener. The form is for uploading an image.
I want to have additional functionality where instead of upload an image from the browser, users can pick from the Dropbox photos using Dropbox Drop-ins Chooser
The flow is, click to launch the "Chooser", pick photos, upload the response from Dropbox via ajax to my controller. My Symfony controller receives a request containing an array of these:
"bytes" : "7466873",
"icon" : "https://www.dropbox.com/static/images/icons64/page_white_picture.png",
"link" : "https://api-content.dropbox.com/1/some-image/IMG_8956.JPG",
"name" : "IMG_8956.JPG",
"thumbnailLink" : "https://api-content.dropbox.com/1/some-image”
What I want to do in my controller, is turn that into a normal $form->handleRequest($request);
so I can use the same form, same validation, same onPostSubmit actions.
Is it possible to "fake" a submitted form completely in a controller?
public function dbUploadAction(Request $request)
{
// check it's an ajax request
if (!$request->isXmlHttpRequest()) {
throw $this->createNotFoundException();
}
$files = $request->get('files');
// create an instance of the form to submit I want to submit to
$document = new Document();
$form = $this->createForm('document', $document);
// do something with $files here
$form->submit( my $files );
if ($form->isValid()) {
// perform some action...
// continue as if form was submitted by user from browser
}
$r = $this->container->get('serializer')->serialize($files, 'json');
return new Response($r);
}
Upvotes: 0
Views: 962
Reputation: 1573
I believe I have done something similar when running some unit tests. I was sending some JSON to the controller via a Test Controller and treating it like a form submission:
// convert the JSON into an array
$data = json_decode($request->getContent(), true);
// instantiate the new Document
$document= new Document();
// create the empty Document form
$form = $this->createForm(new DocumentType(), $document);
// bind the array (of Document fields) to the form, to populate it
$form->bind($data);
// now validate the form
if($form->isValid()){
// business as usual
}
Upvotes: 1