2017-12-18 21:54
浏览 34


I'm trying to submit 2 symfony forms in one submit using ajax

var data = $('#facebookPostTargetForm').serialize();
data = data.concat("
", $('#facebookPostForm').serialize());
    url: '{{ path('facebookpostwizard_new') }}',
    type: "POST",
    data: data,
    dataType: 'html',
    success: function(data){

almost everything is working properly except the case that in my controller when I use $form->handleRequest($request) i get some trouble getting the last field of first form(mostly _token so $form->isValid() always return false) and first field of second one!!!! I don't put a snippet of my controller here because if I only submit one form everything works perfect, it seems to be related to the data.concat() but I've tried a lot of things and it doesn't work. Thanks in advance!

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

  • dongliu6848 2017-12-18 22:19

    Without knowing your PHP code, I can only guess what the issue is. But I suspect you are not handling the Array that you receive correctly. Or rather, you are trying to build something totally different from what you are actually sending.

    concat() does not concatenate strings but Arrays. If you just want to concatenate the serialized query strings of the forms, you can simply use + operator like this:

    var data = $('#facebookPostTargetForm').serialize() + '&' + $('#facebookPostForm').serialize();

    This will make one big query string from both forms and you will have them available as POST variables in the $request object. Note that this will only work if the fields in both forms are named differently. If a field has the same name, form2 will override form1.

    If you use the same field names and want to handle the forms separately, you should post an object instead of a form:

    var data = {
        'form1': $('#facebookPostTargetForm').serializeArray(),
        'form2': $('#facebookPostForm').serializeArray()

    This will submit an object ob objects (or a multidimensional associative array in PHP speech). You can then access them in PHP like this:

    $form1 = $request->get('form1');
    $field1 = $form1['field1']
    解决 无用
    打赏 举报

相关推荐 更多相似问题