通过AJAX生成的Symfony表单FileType:验证错误isSubmitted()始终为false,而processData为:false

时间:2018-12-09 10:54:03

标签: jquery ajax symfony symfony-forms

过去我曾经用AJAX JQUERY上传文件,但现在我正尝试使用symfony FileType进行同样的上传。

问题在于,在正常的工作流程中,我们需要添加contentType: false, processData: false,,但这似乎会导致以下symfony错误:Cannot check if an unsubmitted form is valid. Call Form::isSubmitted() before Form::isValid().

所以isSubmitted()总是错误的,我猜是因为processData: false

我完全不知道如何解决此问题,因为如果不执行contentType: false,则AJAX请求会崩溃。 symfony文档对此不满意。

JAVASCRIPT:

const form_data = $('#newBrandForm').serializeArray();
const json = serializeAsObject(form_data)

    const files = document.getElementById('new_brand_group_logo_logoFile').files;

    if (files.length > 0) {

        let formData = new FormData();

        for (let x = 0; x < files.length; x++) {
            formData.append("attachements", files[x]);
        }

        json['new_brand[group_logo][logoFile]'] = formData

    }

    $.ajax({
        url: `/new-brand-form-handle`,
        type: 'POST',
        cache: false,
        contentType: false,
        processData: false,
        data: json
    })

控制器

function brandFormHandle(Request $request) {

    $em = $this->getDoctrine()->getManager();

    $brandEntity = new Brand();

    // create form
    $form = $this->createForm(NewBrandType::class, $brandEntity);

    // handle
    $form->handleRequest($request); // CRASH HERE

    if ($form->isSubmitted() && $form->isValid()) { 

        $brand = $form->getData();

        // move file
        $someNewFilename = 'newBrand'.'-logo';
        $file = $form['attachment']->getData();
        $file->move($this->directory, $someNewFilename);

        try {

            $em->persist($brand);
            $em->flush();

            $status = 'Brand added';

        } catch (Exception $ex) {
            return $this->json([2, 'insertion error'.$ex]);
        }
        return $this->json([1, $status]);
    }

 //....

}

$request DUMP所以我可以看到其中的文件,但看起来表单只是一个对象,所以我不确定是否可能是问题所在?

Request {#51 ▼
+attributes: ParameterBag {#71 ▶}
+request: ParameterBag {#87 ▼
#parameters: array:1 [▼
  "form" => "[object Object]"
]
}
+query: ParameterBag {#70 ▶}
+server: ServerBag {#35 ▶}
+files: FileBag {#73 ▶}
+cookies: ParameterBag {#72 ▶}
+headers: HeaderBag {#82 ▶}
#content: null
#languages: null
#charsets: null
#encodings: null
#acceptableContentTypes: null
#pathInfo: "/new-brand-form-handle"
#requestUri: "/new-brand-form-handle"
#baseUrl: ""
#basePath: null
#method: "POST"
#format: null
#session: Closure {#111 ▶}
#locale: null
#defaultLocale: "en"
-isHostValid: true
-isForwardedValid: true
basePath: ""
format: "html"
}

//这是console.log(json)的转储,请注意没有文件;我不确定这是否正常

Object
 new_brand[group_description][description]: "description"
 new_brand[group_identification][city]: ""
 new_brand[group_identification][country]: "AU"
 new_brand[group_identification][name]: "name"
 new_brand[group_identification][postcode]: ""
 new_brand[group_identification][streetAdd]: ""
 new_brand[group_identification][street]: "street"
 new_brand[group_identification][website]: "website"
 new_brand[group_logo][logoURL]: "web" 

1 个答案:

答案 0 :(得分:1)

我不知道您为什么混合使用不同的方法(将serializeArray与FormData一起使用),而不仅仅是坚持使用FormData。

似乎您将错误格式的json对象作为ajax请求中的数据传递,因为字段json ['new_brand [group_logo] [logoFile]']包含formData,因此它不是有效的json对象。

实际上,如果您正在使用树枝渲染表单(我想您是这样做的),那么您要做的就是:

var form = $('#newBrandForm')[0]; // You need to use standard javascript object here
var formData = new FormData(form);

$.ajax({
    url: `/new-brand-form-handle`,
    type: 'POST',
    cache: false,
    contentType: false,
    processData: false,
    data: formData
});

现在您应该在控制器中正确提交表单。