javascript - 我可以完全在 Controller 中创建 Symfony 表单提交吗?

标签 javascript php forms symfony

我有一个 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/

相关文章:

javascript - 无 Action 的工作形式

javascript - .before()/.after() 元素不会自动关闭

php - 通过 PHP 回显 json 数组

PHP/JS - 游戏排行榜

php - PHP 中的多行语句到 MySQL 数据库(采用自动递增 ID)

javascript - 为什么输入 val() 没有实时变化?

javascript - MooTools 表单验证器的替代品

javascript - 如何将对象数组拆分为 block

javascript - Angularjs 显示加载微调器

javascript - 学习 JavaScript 的时间名言