我有一个Symfony FormType,包括一个事件监听器中的一些onPostSubmit操作。表单用于上传图片。
我希望有其他功能,而不是从浏览器上传图片,用户可以使用Dropbox Drop-ins Chooser
从Dropbox照片中选择流程是,点击以启动"选择器",选择照片,通过ajax将响应从Dropbox上传到我的控制器。我的Symfony控制器收到一个包含以下数组的请求:
"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”
我想在控制器中执行的操作是将其转换为普通$form->handleRequest($request);
,以便我可以使用相同的表单,相同的验证,相同的onPostSubmit操作。
有可能"假"提交的表格完全在控制器中?
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);
}
答案 0 :(得分:1)
我相信在运行一些单元测试时我做了类似的事情。我通过测试控制器向控制器发送了一些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
}