我有一个 Symfony FormType,包括事件监听器中的一些 onPostSubmit 操作。该表单用于上传图像。
我想要额外的功能,用户可以使用 Dropbox Drop-ins Chooser 从 Dropbox 照片中挑选照片,而不是从浏览器上传图像。
流程是,单击启动“选择器”,选择照片,通过 ajax 将 Dropbox 的响应上传到我的 Controller 。我的 Symfony Controller 收到一个包含以下数组的请求:
"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”
我想要在 Controller 中做的是将其转换为正常的 $form->handleRequest($request);
这样我就可以使用相同的表单,相同的验证,相同的 onPostSubmit 操作。
是否可以在 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);
}
最佳答案
我相信我在运行一些单元测试时做了类似的事情。我通过测试 Controller 向 Controller 发送一些 JSON,并将其视为表单提交:
// 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
}
关于javascript - 我可以完全在 Controller 中创建 Symfony 表单提交吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24982691/